开发者

Ordering a queryset by a generic foreignkey field

开发者 https://www.devze.com 2023-01-24 11:15 出处:网络
I\'m trying to order a queryset by its generic relation names Item.objects.order_by(\'content_object__name\')

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

精彩评论

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