在Django中创建一个多表继承设计 [英] Making a multi-table inheritance design generic in Django

查看:484
本文介绍了在Django中创建一个多表继承设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,有一些链接到我用来参考的页面:一个SO问题,Django文件在通用关系多表继承

First of all, some links to pages I've used for reference: A SO question, and the Django docs on generic relations and multi-table inheritance.

到目前为止,我已经设置了一个多表继承设计。对象(例如:Car,Dog,Computer)可以继承Item类。我需要能够从数据库中检索项目,获取子类,并使用它。我的设计不允许逐个检索不同类型的对象,所以我需要使用Item容器把它们全部包装成一个。一旦我拥有该项目,Django文档说我可以通过引用该模型的名称(例如:myitem.car或myitem.computer)来获取该子类。

So far, I have a multi-table inheritance design set up. Objects (e.g: Car, Dog, Computer) can inherit an Item class. I need to be able to retrieve Items from the DB, get the subclass, and do stuff with it. My design doesn't allow for retrieving the different kinds of objects one by one, so I need to use the Item container to wrap them all into one. Once I have the Item, the Django docs say I can get the subclass by referencing the attribute with the name of the model (e.g: myitem.car or myitem.computer).

我不知道我的项目正在引用哪种类型的对象,那么我怎么能得到孩子?有没有建立这样做的方式?这里有一些其他的想法:(有些比别人更疯狂)

I don't know which type of object my item is referencing, so how can I get the child? Is there a built in way to do this? Here are some other ideas that I had: (some crazier than others)


  1. 我在想我可以添加一些
    GenericForeignKey到
    引用孩子的项目,但我怀疑它
    甚至是父母类合法的
    通过ForeignKey与一个孩子
    类相关。

  2. 我想我可以在Item
    类中有一个
    ForeignKey(ContentType),并找到
    的属性项目,以根据
    ContentType的名称。

  3. 最后,尽管是一个丑陋的方法,我可能会保留一个对象类型的列表,并尝试将其作为一个属性,直到不抛出一个DoesNotExist错误。

正如你所看到的,这些提出的解决方案并不优雅,但我希望我不必使用其中的一个,而这里的某个人可能有一个更好的建议。

As you can see, these proposed solutions are not that elegant, but I'm hoping I won't have to use one of them and someone here might have a better suggestion.

提前感谢

推荐答案

与我的一个项目中的方法2类似:

I have done something similar to method 2 in one of my projects:

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

class BaseModel(models.Model):
    type = models.ForeignKey(ContentType,editable=False)
    # other base fields here

    def save(self,force_insert=False,force_update=False):
        if self.type_id is None:
            self.type = ContentType.objects.get_for_model(self.__class__)
        super(BaseModel,self).save(force_insert,force_update)

    def get_instance(self):
        return self.type.get_object_for_this_type(id=self.id)

这篇关于在Django中创建一个多表继承设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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