确定属于django的字段多对多链接

时间:2012-02-12 04:42:21

标签: django many-to-many

我有4个假设模型:

class Basea(models.Model):
    name = models.CharField("Name", max_length=30)
    type = models.ManyToManyField('Type', blank=True, related_name='types', db_table=u'test_basea_type')

class Baseb(models.Model):
    name = models.CharField("Name", max_length=30)
    type = models.ManyToManyField('Type', blank=True, related_name='types', db_table=u'test_baseb_type')

class Basec(models.Model):
    name = models.CharField("Name", max_length=30)
    type = models.ManyToManyField('Type', blank=True, related_name='types', db_table=u'test_basec_type')

class Type(models.Model):
    name = models.CharField("Name", max_length=30, unique=True)
    baseas = ManyToManyField_NoSyncdb(Basea, blank=True, related_name='type_baseas',  db_table=u'test_basea_type')
    basebs = ManyToManyField_NoSyncdb(Baseb, blank=True, related_name='type_basebs',  db_table=u'test_baseb_type')
    basecs = ManyToManyField_NoSyncdb(Basec, blank=True, related_name='type_basecs',  db_table=u'test_basec_type')

我正在创建一个新的Type,并且我希望在保存新的Type对象后附加多对多链接。在我看来,这很好用:

if form.is_valid(): # All validation rules pass
    new_obj = form.save(commit=False)
    # Do some stuff 
    new_obj.save()
    new_obj.baseas.add(link_object.id) #link_object pulled earlier in the code

所以我将有一个link_object,它可以是Basea,Baseb或Basec。我可以用什么代码来改变最后一行:

    new_obj.baseas.add(link_object.id) 

这样字段对应的是正确的对象类型?因此,如果link_object来自Baseb,代码应执行以下功能:

    new_obj.basebs.add(link_object.id) 

如何更一般地定义该字段名称?

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找GenericForeignKey