Django模型继承和外键 [英] Django Model Inheritance And Foreign Keys

查看:320
本文介绍了Django模型继承和外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个模型,我创建了一个超类,许多其他类共享,然后每个类都有一些独特的功能彼此不同。我们假设A类是超类,类B,C和D是该类的子类。



类B和类C都可以具有D类的倍数,但是我看到最好把外键关系放在D类中,然后再引用它的父类。现在用其他语言,我可以简单地说它与A类有一个ForeignKey关系,然后该语言识别类的真实类型。但是,我不认为它是如何与Python一起使用的。



追求此问题的最佳推荐方法是什么?


$ b $编辑:这大概是我的意思...

  class A(models.Model):
field = models.TextField()

class B(A):
other =< class specific functions>

class C(A):
other2 =<不同的功能>

class D(A):
#我希望D类有一个外键到B或C,但不是两个。

本质上,B类和C类都有多个D类。但是一个特定的D类只属于其中一个。

解决方案

Django Docs



< blockquote>

例如,如果你正在建立一个
数据库places,你将建立
非常标准的东西,如地址,
电话号码等。在数据库中。
那么如果你想在
的地方上建立一个
数据库的餐馆,而不是重复你的
并在
餐厅模型中复制这些字段,你可以使
餐厅有一个OneToOneField到
Place(因为一个餐厅是一个
的地方;实际上,为了处理这个你会
通常使用继承,其中
涉及一个隐含的一对一
关系)。


通常,你只需要餐厅继承自 Place 。可悲的是,您需要我认为的一个黑客:从子类到超类(餐厅 Place


Basically, I have a model where I've created a superclass that many other classes share, and then each of those classes has some unique features that differ from each other. Let's say class A is the superclass, and class B, C, and D are children of that class.

Both class B and class C can have multiples of class D, however I've seen that it's best to put the foreign key relationship in class D, which then refers to its parent class. Now in other languages, I could simply say it has a ForeignKey relationship to class A, and then the language recognizes the classes' true type. However, I don't think that's how it works with Python.

What's the best recommended way of pursuing this issue?

EDIT: Here is roughly what I mean...

class A(models.Model):
    field = models.TextField()

class B(A):
    other = <class specific functionality>

class C(A):
    other2 = <different functionality>

class D(A):
    #I would like class D to have a foreign key to either B or C, but not both.

Essentially, class B and class C both have multiple class D's. But a particular class D only belongs to one of them.

解决方案

From the Django Docs:

For example, if you were building a database of "places", you would build pretty standard stuff such as address, phone number, etc. in the database. Then, if you wanted to build a database of restaurants on top of the places, instead of repeating yourself and replicating those fields in the Restaurant model, you could make Restaurant have a OneToOneField to Place (because a restaurant "is a" place; in fact, to handle this you'd typically use inheritance, which involves an implicit one-to-one relation).

Normally, you would just have Restaurant inherit from Place. Sadly, you need what I consider a hack: making a one-to-one reference from subclass to superclass (Restaurant to Place)

这篇关于Django模型继承和外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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