Django - Multiple optional ForeignKey
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 = 开发者_Python百科models.ForeignKey(Machin3, blank=True, null=True)
I would like Truc
to be linked to one machin
, either machin1
either machin2
or machin3
.
Only one link, so this kind of validation:
machin1 xor machin2 xor machin3
If it is only ever linked to one use a 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')
精彩评论