Django:查询抽象基类 [英] Django: Querying an abstract base class

查看:122
本文介绍了Django:查询抽象基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我正在建立一个足球比赛,每场比赛都有一系列与之相关的事件,与游戏中发生的事情有关。所以有点像这样:

  class Event(models.Model):
time = models.IntegerField()
class Meta:
abstract = True

类目标(事件):
得分= models.ForeignKey('Player')

class PitchInvasion(Event):
number_of_people = models.IntegerField()

class FootballMatch(models.Model):
events = models.ForeignKey('Event')

原谅这个远方的示例,但是它显示了这些子类 Event 可以是任何东西。那么我想要做的就是能够查询所有这些事件,并且及时对它们进行排序,以便按时间顺序查看比赛中发生的情况。



然而,与 abstract = True 事件对象最终得到一个 pitchinvasion_set goal_set 等等。通过设置 abstract = False 并使用具体的继承来解决这个问题吗?我已经看到,这样做是一个坏主意,因为它引入了额外的加入



处理这种情况的最好方法是什么?

解决方案

我同意Peter Rowell的评论 - 模型继承不是你认为的,在我看来很少有用。



一个更好的方法来处理这个问题通用关系。所以你会有一个匹配模型,一个 events = GenericRelation(),每个事件类型都有一个 GenericForeignKey 返回到Match。然后,您可以执行 match.events.all(),并获得该匹配的所有单独事件。



如果你喜欢,你仍然可以为事件的基类使用抽象继承,如果它们都共享一些字段,如描述和时间。


I've got a situation where I'm modelling a football match, and each match has a set of events related to it, that relate to what happened during the game. So something a bit like this:

class Event(models.Model):
    time = models.IntegerField()
    class Meta:
        abstract = True

class Goal(Event):
    scorer = models.ForeignKey('Player')

class PitchInvasion(Event):
    number_of_people = models.IntegerField()

class FootballMatch(models.Model):
    events = models.ForeignKey('Event')

Forgive the far fetched example, but it's there to show that these subclasses of Event could be anything. What I then want to do is to be able to query all those events and order them on time, to give a chronological view of what happened in that match.

However, with abstract = True, the Event objects end up with a pitchinvasion_set, goal_set and so on, . Would this be solved by setting abstract = False and using concrete inheritance? I've read that doing this is a bad idea, as it introduces an extra join.

What's the best way to deal with situations like this?

解决方案

I agree with Peter Rowell's comment - model inheritance isn't what you think it is, and in my opinion is very rarely useful.

A much better way to approach this is with generic relations. So you'd have a Match model, with an events = GenericRelation(), and each of the Event types has a GenericForeignKey back to Match. Then you could do match.events.all() and get all the separate events for that match.

If you like, you can still use abstract inheritance for the base class for the events, if they do all share some fields such as description and time.

这篇关于Django:查询抽象基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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