在django中使用get_or_create添加相关项

时间:2015-09-29 03:12:12

标签: python django django-models

我正在尝试get_or_create django 1.8中的相关记录,如下所示:

在models.py

from django.db import models
import datetime

class ScanItem(models.Model):
    # Stock code
    code = models.CharField(max_length=20)


class Scan(models.Model):
    # Date of scan
    d = models.DateField(primary_key=True, default=datetime.date.today)
    item = models.ForeignKey(ScanItem, related_name='scan_related_scanitem',null=True)

我的代码:

import datetime

# Todays date
d=datetime.date.today()

# Get or create a 'Scan' for today
scan_object, scan_object_created = Scan.objects.get_or_create(
               d__exact=d,
               defaults={'d': d, }
)

# Add an item, relate it to 'Scan'
code = "ABCDEF001"
i, i_created = ScanItem.objects.get_or_create(
               code__exact=code, 
               scan_related_scanitem__exact=scan_object,
               defaults={
                   'scan_related_scanitem': scan_object,
                   'code': code, 
               }
)

当我运行时,我收到错误:

TypeError: 'scan_related_scanitem' is an invalid keyword argument for this function

如何指定ScanItem的默认值,因为它需要与Scan相关联?

2 个答案:

答案 0 :(得分:0)

如错误所示,扫描没有属性scan_related_item。这是相关的名称,用于从ScanItem返回到扫描的链接。转发关系使用实际字段名称,就像任何其他字段一样。

答案 1 :(得分:0)

外键应该在ScanItem对象上,而不是Scan