我正在尝试为我的模型编写测试。
我尝试创建这样的对象:
GiftEn.objects.create(gift_id=1,
name="GiftEn",
description="GiftEn description",
short_description="GiftEn short description",
categories='1',
partner='1',
addresses=2)
但是我收到了这个错误:
File "/home/stasman/giver/giver/giver/gift/test_gift.py", line 29, in setUp
addresses=2)
ValueError: "<GiftEn: GiftEn, GiftEn description, GiftEn short description>" needs to have a value for field "giften" before this many-to-many relationship can be used.
这是我的模特:
class GiftEn(models.Model):
gift = models.ForeignKey(Private, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
description = models.TextField(max_length=1000)
short_description = models.TextField(max_length=500)
categories = models.ManyToManyField(CategoryEn,)
partner= models.ManyToManyField(Partner,)
addresses= models.ManyToManyField(AddressWhereTakeGift,)
def __str__(self):
return '%s, %s, %s' % (self.name, self.description, self.short_description)
class Meta:
ordering = ('-gift__id',)
如何为此模型创建对象?
答案 0 :(得分:0)
通过错误描述,您需要在添加many2many之前创建(保存)GiftEn
对象:
giften = GiftEn.objects.create(
gift_id=1,
name="GiftEn",
description="GiftEn description",
short_description="GiftEn short description")
giften.categories.add('1')
giften.partner.add('1')
giften.addresses.add(2)