문제

I have a django model that can have one of two objects related to it via foreign key (call them object1 and object2). The two other classes are functionally almost identical, but contain slightly different information. At the suggestion of another StackOverflow question, I am using the python method property() to set and get whichever object is present. It looks like the following:

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)

This is a simplified version of the class. I thought everything was working correctly. I was able to set, and get the information, and could display the data held in objectInstance on several of my pages. I'm using django-tables2 to display information in tables, and it too was able to show all the information. However, when I attempt to sort the data (using the convenient arrows that are provided) I get a FieldError:

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

Any idea what's causing this? Or what snippet of code you'd need to see to help determine what the cause is?

EDIT:

So it looks like I'm not the only one with this problem. This post seems to indicate that it's a problem with django-tables2. Non-queryset data ordering in django-tables2

It seems that while the table can display information held in a property it has trouble sorting it.

도움이 되었습니까?

해결책 2

Found an answer.

The problem was that django-tables2 didn't know how to order non-queryset data. This was solved by explicitly giving the table an order_by argument for each column.

Documentation is here: http://django-tables2.readthedocs.org/en/latest/#specifying-alternative-ordering-for-a-column

다른 팁

If you want to use a decorator, see this response.

But the best way is using Generic relations

EDIT

Maybe that:

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

So, you can do:

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

Hope this helps!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top