开发者

Ordering a queryset by a generic foreignkey field

I'm trying to order a queryset by its generic relation names

Item.objects.order_by('content_object__name')

I have the following models in django:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic


class Item(models.Model):
    content_type = models.ForeignKey(ContentType, null=True, blank=True)
    object_id = models.PositiveIntegerField(null=True, blank=True)
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return unicode(self.content_type)


class Work(mode开发者_Go百科ls.Model):
    name = models.CharField(max_length=50, blank=True)

    def __unicode__(self):
        return unicode(self.name)

    def save(self):
        super(Work, self).save()
        item = Item(content_object=self)
        item.save()


class Event(models.Model):
    name = models.CharField(max_length=50, blank=True)

    def __unicode__(self):
        return unicode(self.name)

    def save(self):
        super(Event, self).save()
        item = Item(content_object=self)
        item.save()

Is it only possible to do this? How would you achieve it?

Thanks a lot!


You cannot do this, because content_object is represented in the database as content_type and object_id, so you can only order by one of them!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜