Niorko
Niorko

Reputation: 103

Django - admin_order_field with custom non-related object

How can I use admin_order_field in a method, that has an opposite kind of relation?

Is it possible to use some aggregating query-set function?

class Card(models.Model):
    serial_number = models.CharField(max_length=200)
    ...

class License(models.Model):
    expiration = models.DateTimeField('Expiration')
    card = models.ForeignKey('Card')
    ...

class Pc(models.Model):
    card = models.ForeignKey('Card')
    ...

class PcAdmin(admin.ModelAdmin):
    ...

    def expiration(self, obj):
        try:
            license = License.objects.get(card=obj.card, type="xxx")
            expiration = license.expiration

        except (License.DoesNotExist, TypeError):
            expiration = "N/A"

        return expiration
    expiration.short_description = _("Expiration")
    expiration.admin_order_field = ???

Upvotes: 3

Views: 7696

Answers (1)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 49012

Basically, if you can refer to something the way you do a field, you can use it in admin_order_field.

So, if you wanted to order by the Card's serial_number you could say `admin_order_field = 'card__serial_number'.

Or, if you wanted to use annotations, you could do that by first defining a get_queryset() method that creates the annotation; and then using the new annotation name as your admin_order_field.

But in your case, you can't do it. The problem is the restriction to type="xxx"; there's no way to represent that logic using the field notation.

It might be possible, though, to use extra() to define a custom field with the information you want, and then use that as your admin_order_field.

Upvotes: 7

Related Questions