Django模型继承和外键

编程入门 行业动态 更新时间:2024-10-28 00:18:54
本文介绍了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 :

例如,如果你正在建立一个数据库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模型继承和外键

本文发布于:2023-10-28 00:34:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534984.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!