创建具有M2M和FK关系的模型对象

时间:2011-05-29 21:39:00

标签: django django-models

我有以下型号 -

class Category(models.Model):
    category = models.CharField(max_length=100)

class Credit(models.Model):
    person = models.CharField(max_length=100)
    position = models.CharField(max_length=100)

class Video(models.Model):
    title = models.CharField(max_length=100)
    category = models.ForeignKey(Category)
    credits = models.ManyToManyField(Credit)

我创建了以下CategoryCredit个对象 -

>>> Category.objects.create(category='animation')
>>> Category.objects.create(category='drama')
>>> Credit.objects.create(person='john', position='director')
>>> Credit.objects.create(person='tom', position='writer')

然后我'得到'那四个对象 -

>>> cat1 = Category.objects.get(category='animation')
>>> cat2 = Category.objects.get(category='drama')
>>> cred1 = Credit.objects.get(person='john')
>>> cred2 = Credit.objects.get(person='tom')

但是我在创建Video对象时遇到了困难。我如何创建以下两个对象?

1) Video.objects.create(title='little italy', category=cat1, credits=cred1)  ??
2) Video.objects.create(title='new film', category=cat2, credits=cred1, cred2)  ??

谢谢。

1 个答案:

答案 0 :(得分:4)

>>> v1 = Video.objects.create(title='little italy', category=cat1)
>>> v1
<Video: little italy>
>>> v1.credits.add(cred1)

...等...