Django - 多个可选的ForeignKey

时间:2011-07-21 09:04:31

标签: python django validation model foreign-keys

class Truc(models.Model):
  name = models.CharField(max_length=50, unique=True)
  machin1 = models.ForeignKey(Machin1, blank=True, null=True)
  machin2 = models.ForeignKey(Machin2, blank=True, null=True)
  machin3 = models.ForeignKey(Machin3, blank=True, null=True)

我希望Truc与一个machin相关联,machin1 machin2machin3

只有一个链接,所以这种验证:

machin1 xor machin2 xor machin3

1 个答案:

答案 0 :(得分:0)

如果仅使用generic relation

链接
class Truc(models.Model):
    name = models.CharField(max_length=50, unique=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    machin_object = generic.GenericForeignKey('content_type', 'object_id')