[英]django manytomany field add dynamically
我在 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 字段做同样的事情?
如果您正在考虑如何将数据添加到多对多列表
your_object.ones.add(what_you_want_to_add)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.