django manytomany字段动态添加

时间:2015-12-13 10:12:03

标签: python django many-to-many

我在Django中有两个常规模型:

class One(models.Model):
    title = models.CharField('title', max_length=255, blank=True, null=True)

class Two(models.Model):
    first_field = models.ForeignKey(One)
    ones = models.ManyToManyField(CouponType, related_name='ones_two')

我想动态地做这样的事情:

item_one = One()
item = Two()
item.ones.add(item_one)

适用于外键:

field = Two._meta.get_field('first_field')
kwargs = {field_name: value}
field_value = field.rel.model.objects.get_or_create(**kwargs)[0]
setattr(Two, 'first_field', field_value)

如何为ManyToMany字段执行相同操作?

1 个答案:

答案 0 :(得分:0)

如果您要考虑如何将数据添加到多对多列表

your_object.ones.add(what_you_want_to_add)