【问题标题】:Using Property to duck type two models使用属性来回避类型两个模型
【发布时间】:2013-06-20 16:47:59
【问题描述】:

我有一个 django 模型,它可以通过外键拥有两个与之相关的对象之一(称它们为 object1object2)。其他两个类在功能上几乎相同,但包含的信息略有不同。在另一个 StackOverflow 问题的建议下,我使用 python 方法property() 来设置和获取存在的任何对象。如下所示:

class Master(models.Model):
    object1=models.ForeignKey(Object1, null=True)
    object2=models.ForeignKey(Object2, null=True)

    def get_object(self):
        if self.object2_id:
            return self.object2
        else:
            return self.object1

    def set_object(self, instance):
        if isinstance(instance, Object2):
            self.object2 = instance
            self.object1 = None
        else:
            self.object2 = None
            self.object1 = instance

    objectInstance = property(get_object, set_object)

这是该类的简化版本。我认为一切正常。我能够设置和获取信息,并且可以在我的几个页面上显示objectInstance 中保存的数据。我正在使用 django-tables2 在表格中显示信息,它也能够显示所有信息。但是,当我尝试对数据进行排序(使用提供的方便箭头)时,我得到一个 FieldError:

 FieldError at /workflow/list/request/
 Cannot resolve keyword u'objectInstance' into field. Choices are: object1, object2

知道是什么原因造成的吗?或者您需要查看哪些 sn-p 代码来帮助确定原因是什么?

编辑:

看来我不是唯一一个遇到这个问题的人。这篇文章似乎表明这是 django-tables2 的问题。 Non-queryset data ordering in django-tables2

看起来虽然表格可以显示property 中保存的信息,但对其进行排序有困难。

【问题讨论】:

    标签: python django django-tables2


    【解决方案1】:

    如果你想使用装饰器,请参阅this response

    但最好的方法是使用Generic relations

    编辑

    也许:

    class Master(models.Model):
        content_type = models.ForeignKey(ContentType)
        object_id = models.PositiveIntegerField()
        objectInstance = generic.GenericForeignKey('content_type', 'object_id')
    

    所以,你可以这样做:

    >>> t = Master(objectInstance=Object2())
    >>> t.save()
    >>> t.objectInstance
    <Object2: a_description>
    >>> t.objectInstance = Object1()
    >>> t.save()
    >>> t.objectInstance
    <Object1: a_description>
    

    希望这会有所帮助!

    【讨论】:

    • 我对此有点困惑。是不是说我应该有另一个名为ObjectInstance 的类,然后在其中包含该代码,以及与 ObjectInstance 的外键关系?
    • 我自己找到了答案(见下文)。它最终只是 django-tables 2 不理解数据结构并且需要给出明确的order_by 参数的问题。
    【解决方案2】:

    找到了答案。

    问题在于 django-tables2 不知道如何排序非查询集数据。这是通过显式地为表的每一列提供一个 order_by 参数来解决的。

    文档在这里:http://django-tables2.readthedocs.org/en/latest/#specifying-alternative-ordering-for-a-column

    【讨论】:

      猜你喜欢
      • 2011-06-23
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      相关资源
      最近更新 更多