以下是一些Django模型:
class User (Model):
name = CharField (max_length=100)
class ThingVersion (Model):
timestamp = DateTimeField (auto_now_add = True)
class ThingPartition (Model):
version = ForeignKey (ThingVersion)
partition_number = IntegerField ()
class UserInPartition (Model):
user = ForeignKey (User)
version = ForeignKey (ThingVersion)
partition_number = IntegerField ()
class Meta:
unique_together = (('user', 'version'))
我故意没有做“明显”的事情,这是
class UserInPartition (Model):
user = ForeignKey (User)
partition = ForeignKey (ThingPartition)
因为我需要
unique_together
约束,所以如果使用更规范化的partition = ForeignKey (ThingPartition)
方法,则无法表达AFAIK。如何表达
UserInPartition.(version,partition_number)
对是ThingPartition
的外键?或者,是否可以使用归一化的
partition = ForeignKey (ThingPartition)
方法并将UserInPartition
模型约束为每个partition_number
仅包含一个(user,version)
? 最佳答案
我试图了解您想要实现的目标,以便提供更好的答案。为什么在partition和thingpartition中的用户都有分区号?
但是您可以做的是将ThingPartition转换为用于多对多关系的Through模型。
https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ManyToManyField.through
基本上,使用直通模型将完全满足您的要求-
有一个模型,您可以在分区,分区号和版本中指代用户
对该模型中的所有三件事共同实施唯一性
基本上,您的设置应如下所示:
class User (Model):
name = CharField (max_length=100)
something_that_makes_sense = ManyToManyField(ThingVersion, through=ThingPartition)
class ThingVersion (Model):
timestamp = DateTimeField (auto_now_add = True)
class ThingPartition (Model):
user = ForeignKey (User)
version = ForeignKey (ThingVersion)
partition_number = IntegerField ()
class Meta:
unique_together = ('user', 'version', 'partition_number')
根据我所掌握的有限知识,这将是我最好的报价。