如何在可重用的Django应用程序中建立外键? [英] How to Model a Foreign Key in a Reusable Django App?

查看:122
本文介绍了如何在可重用的Django应用程序中建立外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的django网站我有两个应用程序,博客和链接。博客有一个模型博客,链接有一个模型链接。这两件事情之间应该有一对多的关系。每个博客文章有很多链接,但每个链接都有一个博客文章。简单的答案是将外键放在链接模型中的blogpost中。

In my django site I have two apps, blog and links. blog has a model blogpost, and links has a model link. There should be a one to many relationship between these two things. There are many links per blogpost, but each link has one and only one blog post. The simple answer is to put a ForeignKey to blogpost in the link model.

这很好,但是有一个问题。我想使链接应用程序可重用。我不希望它依赖于博客应用程序。我想能够在其他网站再次使用它,也可能将链接与其他非blogpost应用和模型相关联。

That's all well and good, however there is a problem. I want to make the links app reusable. I don't want it to depend upon the blog app. I want to be able to use it again in other sites and perhaps associate links with other non-blogpost apps and models.

一般的外键似乎可能是答案,但不是真的。我不希望链接能够与我的网站中的任何模型相关联。只是我明确指定的那个。而且我从以往的经验可以看出,在数据库使用方面可能会出现使用通用外键的问题,因为您无法通过常规外键执行select_related方式。

A generic foreign key seems like it might be the answer, but not really. I don't want links to be able to associate with any model in my site. Just the one that I explicitly specify. And I know from prior experience that there can be issues using generic foreign keys in terms of database usage because you can't do a select_related over a generic foreign key the way you can with a regular foreign key.

建立这种关系的正确方式是什么?

What is the "correct" way to model this relationship?

推荐答案

如果你认为链接应用程序将始终指向一个应用程序,然后一种方法是将外部模型的名称作为包含应用程序标签的字符串而不是类引用传递( Django docs说明)。

If you think the link app will always point to a single app then one approach would be to pass the name of the foreign model as a string containing the application label instead of a class reference (Django docs explanation).

换句话说,而不是: / p>

In other words, instead of:

class Link(models.Model):
    blog_post = models.ForeignKey(BlogPost)

do:

from django.conf import setings
class Link(models.Model):
    link_model = models.ForeignKey(settings.LINK_MODEL)

和您的settings.py:

and in your settings.py:

LINK_MODEL = 'someproject.somemodel'

这篇关于如何在可重用的Django应用程序中建立外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆