django - 通用关系是多对一还是多对多?

标签 django database-design django-models relational-database

我面临以下问题:

我想创建一个结果模型(又名:优点和继续模型),它可以关联到不同的模型 ( Generic Relationship Django ) 并包含以下信息:

Consequences : Boolean (Positive or Negative)
Of : Model_Primary_Key
Reason : Text
Author : User_Primary_Key
Users_likes : List<Users>

一个对象(属性)可以有多种结果,但一个结果只会属于一个结果,因此它应该是多对一的关系。

Entity relational diagram

问题是我不知道结果模型和其他模型之间的关系是多对一还是多对多。

通常,当您有一对多时,具有多个的部分包含另一个的外键,但在这里,如果我这样做,外键将是AuthorOf 并且该集合将是复合主键,但如果我在这里这样做,则用户不能对每个对象获得超过一个结果,这应该是可能的。

所以我发现的唯一解决方案是向结果添加一个 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/

相关文章:

python - Django 高级搜索

database - 与实体关联的描述性标签是否应该存储在单独的数据库表中?

python - 在 models.py : Django rest framwork 中导入序列化器

python - Django REST Framework 外键 - NOT NULL 约束失败

python - 如何在 Django 模型上将月份表示为字段

javascript - 在 Django 表单中动态显示和隐藏字段

python - 访问网站 : syntax error (admin. py,第 4 行时出现 Django 错误

ruby-on-rails - 在 Rails 中,如何将多个模型关联到一个将统领所有模型的模型?

database-design - 如何在关系数据库中对多语言实体建模

python - Django 中的多个数据库破坏了测试隔离。如何解决?