[英]ValueError: Cannot assign error in Django foreign key
我的项目中有三个不同的 Django 应用程序:问题、答案和学生。 我为 Question 和 Student 创建了演示数据,我希望它们的对象是 Answer 的外键。
下面是 Answer 的迁移文件。
from django.db import migrations
from django.apps import apps
questions = apps.get_model('questions', 'Question')
students = apps.get_model('students', 'Student')
def create_data(apps, schema_editor):
Answer = apps.get_model('answers', 'Answer')
Answer(question=questions.objects.get(pk="1"),
student=students.objects.get(pk="2"), answer="Main function").save()
class Migration(migrations.Migration):
dependencies = [
('answers', '0001_initial'),
]
operations = [
migrations.RunPython(create_data)
]
当我运行python manage.py migrate
,出现以下错误。
ValueError: Cannot assign "<Question: What is this?>": "Answer.question" must be a "Question" instance.
请有人帮我解决这个问题吗?
检查是否有带有您需要的 ID 的问题和学生行,然后使用 ID 设置外键。 例子:
answer = Answer(answer="Main function")
answer.question_id = 1
answer.student_id = 2
answer.save()
PS 不需要从django.apps
导入apps
,它是create_data
函数的第一个参数。 我建议改用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.