Django:查询抽象基类

时间:2023-01-09 06:44:01

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.

原谅了这个备受瞩目的例子,但是它表明Event的这些子类可以是任何东西。我当时想要做的是能够查询所有这些事件并按时订购,以按时间顺序查看该匹配中发生的事情。

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.

但是,使用abstract = True,Event对象最终会有一个pitchinvasion_set,goal_set等等。这可以通过设置abstract = False并使用具体的继承来解决吗?我已经读到这样做是一个坏主意,因为它引入了额外的连接。

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

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

1 个解决方案

#1


2  

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.

更好的方法是使用通用关系。所以你有一个Match模型,有一个events = GenericRelation(),每个Event类型都有一个GenericForeignKey回到Match。然后你可以做match.events.all()并获得该匹配的所有单独事件。

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.

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

#1


2  

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.

更好的方法是使用通用关系。所以你有一个Match模型,有一个events = GenericRelation(),每个Event类型都有一个GenericForeignKey回到Match。然后你可以做match.events.all()并获得该匹配的所有单独事件。

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.

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