gpt4 book ai didi

sql - 我应该如何建模模型可以与 Django 中不同类型的实体相关的模式

转载 作者:行者123 更新时间:2023-11-29 13:48:08 24 4
gpt4 key购买 nike

架构选项 1:https://gist.github.com/guyjacks/6ec4c1b0fa41b3f666f5c6adf2dfaf89

架构选项 2:https://gist.github.com/guyjacks/4838cd76b2f924629d2a3f2ba316a504

我想这实际上是两个问题:

  1. 从关系数据库的角度推荐哪种架构?
  2. 在 Django 中是否有一种惯用的方法来对任一模式进行建模?

干杯!

最佳答案

一种方法是使用Generic Relations:

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

在模型中你想关联各种模型:

class SomeModel(models.Model):
...

# Below the mandatory fields for generic relation
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()

在你想要相关的模型中:

from django.contrib.contenttypes.fields import GenericRelation

class SomeOtherModel(models.Model):
...
# The relation
your_field = GenericRelation(SomeModel)

如果您希望能够使用反向查询,请从文档中查看:

related_query_name

The relation on the related object back to this object doesn’t exist by default. Setting related_query_name creates a relation from the related object back to this one. This allows querying and filtering from the related object.

使用它们时应小心,因为它们会迅速增加复杂性。

更多信息链接:

https://docs.djangoproject.com/en/1.11/ref/contrib/contenttypes/#generic-relations https://simpleisbetterthancomplex.com/tutorial/2016/10/13/how-to-use-generic-relations.html

关于sql - 我应该如何建模模型可以与 Django 中不同类型的实体相关的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45087813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com