Django模型子类化:通过查询超类获取子类 [英] Django model subclassing: Get the subclass by querying the superclass

查看:233
本文介绍了Django模型子类化:通过查询超类获取子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

class BaseMedium(models.Model):
    title = models.CharField(max_length=40)
    slug = models.SlugField()

class A(BaseMedium):
    url = models.URLField()

class B(BaseMedium):
    email = models.EmailField()

我现在想查询每个BaseMedium。

I now want to query every BaseMedium.

b = BaseMedium.objects.all()

如何在不知道子类型的情况下打印包括子类字段在内的每个信息?

How do I print every information including the subclass fields without knowing what the subclass type is?

b [0] .a 将打印信息,如果 b [0] 实际上与一个实例,但如果它与 B 相关,则会打印 DoesNotExist 异常。

b[0].a would print the information if b[0] is actually related to an A instance but if it's related to B it would print an DoesNotExist Exception.

这是有道理的,但我想有一个常见的变量或方法返回相关对象。

This makes sense but I'd like to have a common variable or method that returns the related object.

也许我的数据库布局不是真的很好,以这种方式查询,如果这样我会很高兴,如果你建议一个更好的布局。

Maybe my Database layout isn't really great to query that way if so I'd be glad if you'd recommend a better layout.

我考虑使用 GenericForeignKey

class Generic(models.Model):
    basemedium = models.ForeignKey('BaseMedium')
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    object = generic.GenericForeignKey('content_type', 'object_id')

但这个解决方案似乎很复杂,我想你们有更好的解决方案。 >

but this solution seems to be to complicated and I think you guys have better solutions.

推荐答案

您应该检查解决方案由Ca发布rl Meyer 前一段时间。它内部使用ContentType方法,但它非常优雅地封装了它。

You should check the solution posted by Carl Meyer some time ago. It internally uses the ContentType approach, but it encapsulates it very elegantly .

他还指出了一种替代的,更有效的解决方案,不需要存储ad字段,但它只适用于直接的子类。如果您有几个继承级别,则第一个解决方案会更好。

He also points to an alternative, and more efficient solution, that doesn't need to store an aditional field on the database, but it will only work for direct child classes. If you have several inheritance levels, the first solution is better.

这篇关于Django模型子类化:通过查询超类获取子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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