我面临以下问题:
我想创建一个结果模型(又名:优点和继续模型),它可以关联到不同的模型 ( Generic Relationship Django ) 并包含以下信息:
Consequences : Boolean (Positive or Negative)
Of : Model_Primary_Key
Reason : Text
Author : User_Primary_Key
Users_likes : List<Users>
一个对象(属性)可以有多种结果,但一个结果只会属于一个结果,因此它应该是多对一的关系。
问题是我不知道结果模型和其他模型之间的关系是多对一还是多对多。
通常,当您有一对多时,具有多个的部分包含另一个的外键,但在这里,如果我这样做,外键将是Author和Of 并且该集合将是复合主键,但如果我在这里这样做,则用户不能对每个对象获得超过一个结果,这应该是可能的。
所以我发现的唯一解决方案是向结果添加一个 id 作为主键,所以最终它的工作方式就像多对多关系,因为最后的工作方式就像 Associative entity .
那么在我的实体关系图的最后,我应该如何表示这种关系?一对多还是多对多?
最佳答案
您可以使用 djangos 隐式 AutoField
作为主键,并且不添加 unique_together
约束来克服您描述的障碍。
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Consequence(models.Model):
# implicit AutoField
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
author = models.ForeignKey(User)
is_positive_consequence = models.BooleanField()
reason = models.CharField(max_length=200)
class ConsequenceLike(models.Model):
# implicit AutoField
parent = models.ForeignKey(Consequence)
user = models.ForeignKey(User)
这样,一个User
就可以创建许多指向同一对象的Consequence
实例,因为没有唯一约束。
这为您以后的过滤提供了很大的灵活性:
# created by this user
user_instance.consequence_set.all()
# created by this user, filtered by content type
from myapp.models import MyCarModel
user_instance.consequence_set.filter(
content_type=ContentType.objects.get_for_model(MyCarModel))
# created by this user, filtered by object instance
my_car = MyCarModel.objects.first()
user_instance.consequence_set.filter(
content_type=ContentType.objects.get_for_model(my_car.model),
object_id=my_car.pk)
关于django - 通用关系是多对一还是多对多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49980546/