Django中间多个到多个字段的问题

时间:2015-11-04 10:32:32

标签: python django django-models

我在通过多对多关系与其他模型相关的模型中插入数据。我试图使用add()在多对多字段中添加值,但这不起作用并引发此错误Cannot set values on a ManyToManyField which specifies an intermediary model.

我阅读了文档,发现我们无法将set(), add(), create()用于中间模型。

以下是我的模特:

class Venue(MPTTModel):
    organisation = models.ForeignKey(Organisation, verbose_name=_('organisation'))
    name = models.CharField(_('name'), max_length=100)
    description = models.TextField(_('description'), null=True, blank=True)
    address = models.ForeignKey(Address, verbose_name=_('address'))
    org_users = models.ManyToManyField(PortalUser, through='OrgMapping', verbose_name=_('org users'))
    modified_at = models.DateTimeField(_('modified at'), auto_now=True)

class OrgMapping(models.Model):
    host_group = models.ForeignKey(OrgHostGroups, verbose_name=_('host group'))
    org_user = models.ForeignKey(PortalUser, verbose_name=_('org user'))
    venue = models.ForeignKey(Venue, verbose_name=_('venue'))
    org_roles = models.ManyToManyField(OrgRole, verbose_name=_('org roles'))
    org_permissions = models.ManyToManyField(OrgPermission, verbose_name=_('org permissions'), blank=True)
    created_at = models.DateTimeField(_('created at'), auto_now_add=True)
    modified_at = models.DateTimeField(_('modified at'), auto_now=True)
    is_deleted = models.BooleanField(_('is deleted'), default=False)



def create_org_venue(org, name, desc, address, org_users):
    """
    org_users must be a list or portal users pk's
    """

    parent = get_or_none(Venue, organisation__name='TeraMatrix')
    venue = Venue(organisation=org,
                            name=name,
                            description='Head Office',
                            address=address)
    venue.save()
    # save org_users to above venue
    for user in org_users:
        # venue.org_users.add(user)
        venue.org_users = get_or_none(PortalUser,pk=user)
        venue.save()
    return venue

现在,如果我尝试使用create_org_venue来尝试场地,则会引发错误。知道我怎么做这个

修改: -

class OrgHostGroups(MPTTModel):
    organisation = models.ForeignKey(Organisation, verbose_name=_('organisation'))
    name = models.CharField(_('name'), max_length=100)
    description = models.TextField(_('description'), null=True, blank=True)
    org_users = models.ManyToManyField(PortalUser, through='OrgMapping', verbose_name=_('org users'))
    venues = models.ManyToManyField(Venue, through='OrgMapping', verbose_name=_('venues'))

正如您所见,Venue模型通过orgmapping进行映射,并且还需要orghostgroup,它需要场地和映射。所以我们可以说是循环关系。

1 个答案:

答案 0 :(得分:1)

使用中间模型时无法使用OrgMapping.objects.create( venue=venue, org_user=user, # set all the other required OrgMapping fields here ) ,因为这不允许您为中间模型上的额外字段指定值。

相反,只需创建中间模型的实例。

        jcid_no           die_no          qty
       jcid-085951         12345            2
       jcid-085951         12345            2

有关详细信息,请参阅extra fields on many-to-many relationships上的文档。