gpt4 book ai didi

python - 具有链接 FK 的 Django 可重用应用程序?

转载 作者:行者123 更新时间:2023-11-28 17:46:50 25 4
gpt4 key购买 nike

我有以下场景。

我有一个名为“联系人”的现有应用程序,它的模型是号码名称

我想创建一个名为“取消订阅”的新应用程序,并且我想让它可重用

这是我的问题:

在名为 unsubscribe 的新应用程序中,它的模型需要一个与联系人号码相关的外键。现在这意味着它现在与“联系人”相关联,我不能将它用于我的电子邮件应用程序。 Django 如何从可重用的角度处理这个问题?

最佳答案

您可以使用 Generic Relations并创建一个 Generic Foreign Key取消订阅模型到联系人模型的关系。这允许您抽象化取消订阅和其他对象之间的关系,将它们连接到项目中模型的任何实例。

A normal ForeignKey can only “point to” one other model, which means that if the TaggedItem model used a ForeignKey it would have to choose one and only one model to store tags for. The contenttypes application provides a special field type (GenericForeignKey) which works around this and allows the relationship to be with any model

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Unsubscription(models.Model):
name = ...

# These two fields allow you to manage the model & instance of object that
# this unsubscribe model instance is related to
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
# This gives you an easy way to get access to the actual instance of the
# instance above
content_object = generic.GenericForeignKey('content_type', 'object_id')


# On the reverse end of the relationship you can add a Generic relation to
# easily get access to all unsubscriptions related to this contact via the GFK
from myapp.models import Unsubscription
class Contact(models.Model):
name = ...

unsubscribtions = generic.GenericRelation(Unsubscribtion)

关于python - 具有链接 FK 的 Django 可重用应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16913178/

25 4 0
文章推荐: python - 当最后一个 x 值等于刻度时,避免绘图边缘上的点
文章推荐: python - 使用Flask解决静态路由和动态路由的冲突
文章推荐: python - 如何在 IPython 中使用全局变量
文章推荐: python - lxml 找到 ID 为 ='post-[0-9]*' 的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com