2013-04-26 189 views
2

我有一个django模型继承的问题。这是我有:Django模型继承和Meta类

class Room(models.Model): 
    name = models.CharField(max_length=32) 

class Container(models.Model): 
    size = models.IntegerField(default=10) 
    ... 

class BigBox(Container): 
    room = models.ForeignKey(Room) 
    ... 

class SmallBox(Container): 
    big_box = models.ForeignKey(BigBox) 
    ... 

class Stuff(models.Model): 
    container = models.ForeignKey(Container) 
    ... 

    class Meta: 
     ordering = ('container__???__name',) 

所以,这一点,我能够把一些东西放在大箱子或小盒子,这是在大箱子。

我怎样才能知道我的东西字段'容器'的类型,以访问房间的名称?我知道我可以写

container__big_box__room__name 

container__room__name 

,但我想是这样

container__get_room__name. 

这可能吗?

谢谢,

Alex。

回答

0

对于您关于订购元的实际问题,我的回答是:我不认为这是可能的。

现在,一些解决方法:

我会重新考虑你的模型层次结构。 对我来说,可以装在另一个盒子/容器中的盒子/容器仍然是一个盒子。

看一看这个替代:

class Container(models.Model): 
    size = models.IntegerField(default=10) 
    room = models.ForeignKey(Room) 
    ... 

class ContainableContainer(Container): 
    parent_container = models.ForeignKey('self', null=True) 
    ... 

class Stuff(models.Model): 
    container = models.ForeignKey(Container) 
    ... 

    class Meta: 
     ordering = ('container__room__name',) 

有了这个解决方案,你并不真的需要一个不同的模型,它们都是容器,其中cointainer的cointainer是可选的。所以,你可以按照你的想法进行排序。

你必须小心房间现场管理。您需要使每个包含的集装箱房间与其集装箱的房间相同。

例如,重写保存方法或使用pre_save信号:

class ContainableContainer(Container): 
     parent_container = models.ForeignKey('self', null=True) 
     ... 

    def save(self, *args, **kwargs): 
     self.room = self.parent_container.room 
     super(ContainableContainer, self).save(*args, **kwargs) 

EDIT:这实际上是树状层次结构。为了使它更高效的查询django-mptt将是一个不错的选择。 它允许您获取根容器或使用更有效的查询遍历盒层次结构。 我没有任何经验,但它确实是最好的解决方案。

+0

我不明白我的small_box可能在不同的房间,她的big_box,因为small_box链接到一个特定的big_box。 你的层次结构非常酷,但是,我的small_box必须是一个大的。我希望这是由数据库保存,而不是保存方法。 我希望我很清楚,谢谢你,并问我如果你想要一些精度的问题。 Alex。 – Alex 2013-04-26 14:38:37

+0

@亚历克斯对不起。我对不同房间的反思是错误的。我的建议层次结构实际上就是这种情况。这具有冗余字段的缺点,因为每个ContainableContainer都会有一个指向其根目录房间的字段。 – 2013-04-26 14:45:10

+0

没问题;)是的,这是我第一次尝试,并且如您所做的那样,我忽略了保存方法。但是我的实习导师会更喜欢这个由数据库来处理。实际上,实际的问题是:是否有一种方法可以在字段排序中使用函数,例如ordering =('box__get_room()__ name'))?我在这个问题上没有找到任何东西,所以可能不是。我会和我的导师重新考虑你的方法,也许我会在星期一带着好消息回来;)谢谢你的时间,祝你有美好的一天。 – Alex 2013-04-26 14:52:05