Django中的多值主键

时间:2021-08-19 08:22:26

I need to enforce a property in a model such that for each 'User' field in this particular table, it's corresponding 'Post' field is distinct - and vice versa (i.e., for each particular 'Post' field, the corresponding 'User' field is distinct). I'm not sure how to do this in Django. I think one approach would be to define the ('User', 'Post') tuple to be a primary key, but it doesn't seem that Django supports this. Is there any other way to enforce this constraint at the field specifications of a Django model (i.e., without doing all the checks in a save() function)? Thanks, appreciate any feedback!

我需要在模型中强制执行属性,以便对于此特定表中的每个“用户”字段,它的相应“发布”字段是不同的 - 反之亦然(即,对于每个特定的“发布”字段,相应的“用户”领域是截然不同的)。我不知道如何在Django中这样做。我认为一种方法是将('User','Post')元组定义为主键,但似乎Django不支持这一点。有没有其他方法可以在Django模型的字段规范中强制执行此约束(即,不执行save()函数中的所有检查)?谢谢,感谢任何反馈!

1 个解决方案

#1


1  

You can use unique-together in the Meta class.

您可以在Meta类中使用unique-together。

#1


1  

You can use unique-together in the Meta class.

您可以在Meta类中使用unique-together。