2012-02-12 57 views
0

我有4個假設的模型領域:確定屬於許多人Django的許多鏈接

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') 

我創建一個新的類型,我要附加的新類型的對象後,許多一對多鏈接被保存。在我看來,這工作得很好:

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,或PCA的省域。什麼代碼,我可以用它來改變最後一行:

new_obj.baseas.add(link_object.id) 

使得字段對應於正確的對象類型?所以,如果link_object來自Baseb,代碼應執行的功能:

new_obj.basebs.add(link_object.id) 

如何該字段名稱更一般定義的?

回答