指向同一模型的通用关系

时间:2013-08-08 22:42:40

标签: django django-models django-contenttypes

我目前遇到通用密钥问题。我不知道如何轻松设置两个指向同一模型的GenericRelation:

假设我们有以下课程:

class Pen(models.Model):
  color = models.CharField(choices=COLORS)

  content_type = models.ForeignKey(ContentType)
  object_id = models.PositiveIntegerField()
  item = generic.GenericForeignKey('content_type', 'object_id')

class PencilCase(models.Model):

  ballpoint_pens = generic.GenericRelation(Pen, related_name="ballpointpencil+")
  fountain_pens = generic.GenericRelation(Pen, related_name="fountainpencil+")

问题是Django无法区分圆珠笔和fountain_pen。正如预期的那样,每支笔都在ballpoint_pens列表和fountain_pens列表中。

有人对此有所了解吗?

1 个答案:

答案 0 :(得分:0)

实际上,这很容易做到,我刚刚在两个子类中继承了我的类Pen并更改了GenericRelation参数,对不同意见抱歉:

class BallPointPen(Pen):
  pass

class FountainPen(Pen):
  pass

class PencilCase(models.Model)
  ballpoint_pens = generic.GenericRelation(BallPointPen, related_name="ballpointpencil+")
  fountain_pens = generic.GenericRelation(FountainPen, related_name="fountainpencil+")

它就像一个魅力。