2013-01-19 89 views
0

好吧,这可能是其他人很容易解决,但我真的很困惑如何解决这个问题。django模型帮助涉及m2m和foreignkey

所以,首先,我有一个模型A有多个字段与特定表具有多对多关系。因此,例如

class A(models.Model): 
    field1 = models.ManyToMany('field1Collection') 
    field2 = models.ManyToMany(field2Collection') 

class field1Collection(models.Model): 
    description = models.TextField() 

class field2Collection(models.Model): 
    description = models.TextFIeld() 

无论如何,这是我想要完成的。我需要编写另一个可以保持排名系统的模型。因此,例如,我想创建一个记录,我可以定义

我有队伍的x个(3例):

  1. field1Collection对象3
  2. field2Collection对象6
  3. field1Collection对象2

所以我基本上想要能够从我的field1Collection和field2Collection表中选择对象并为它们分配等级。我试图想出使用foreignkeys和m2m字段的方案,但它们都出错了,因为模型需要知道我需要引用哪些collection集合的时间“提前”。这有很多意义吗?谁能帮忙?

回答

0

就可以解决这个使用GenericForeignKey关系

from django.db import models 
from django.contrib.contenttypes.models import ContentType 
from django.contrib.contenttypes import generic 

class RankItem(models.Model): 
    rank = models.IntegerField() 
    content_type = models.ForeignKey(ContentType) 
    object_id = models.PositiveIntegerField() 
    content_object = generic.GenericForeignKey('content_type', 'object_id') 

    def __unicode__(self): 
     return self.rank 

正常F​​oreignKey的只能用“点”另外一个模式,这意味着,如果RankItem模型中使用一个ForeignKey那就要选一个且只有一个模型来存储标签。 contenttypes应用程序提供了一种专门的字段类型,它可以解决这个问题,并且可以与任何模型建立关系

0

你需要那个field1Collection和filed2Collection有一个共同的祖先类,你可以引用一个foreignKey。关于继承请参阅django文档。

+0

您推荐什么样的继承? – asaji