使用一对一和外键字段创建新模型实例

时间:2017-11-08 19:06:08

标签: python django django-models

型号:

class BurrowedBook(models.Model):
    # Fields
    borrow_date = models.DateField()
    return_date = models.DateField()
    actual_return_date = models.DateField(null=True)

    # Relationship Fields
    book_copy = models.OneToOneField(BookCopy)
    burrowed_by = models.ForeignKey(Member)

保存新实例:

member = Member.objects.filter(member_id=memberId)
book_copy = BookCopy.objects.filter(book=book, copy_number=book_copy_id)

BurrowedBook.objects.create(borrow_date=borrow_date, 
                              return_date=return_date, 
                              book_copy=book_copy, burrowed_by=member)

如何保存此模型的新实例?我在一对一场和外键场遇到麻烦。

我收到了这个错误:

Cannot assign "<QuerySet []>": "BurrowedBook.book_copy" must be a 
"BookCopy" instance.

2 个答案:

答案 0 :(得分:1)

出现错误是因为您尝试分配查询集Cannot assign "<QuerySet []>"来解决您必须使用get的问题,返回单个对象而不是查询集

member = Member.objects.get(member_id=memberId)
book_copy = BookCopy.objects.get(book=book, copy_number=book_copy_id)

另一种选择是从查询集中获取第一个对象:

book_copy = BookCopy.objects.filter(book=book, copy_number=book_copy_id)[0]

答案 1 :(得分:0)

就像错误所说的那样,你必须拥有一个BookCopy实例并将该实例分配给你的book_copy。您必须先创建一个BookCopy(需要检查您的BookCopy模型),例如 - &gt; book_copy = BookCopy.objects.create()。在保存实例方面,请查看详细信息:https://docs.djangoproject.com/en/1.11/ref/models/querysets/#create