pythondjango
pythondjango

Reputation: 1671

Django admin sorting

In my admin.py is there a way to sort this data set by latest date? As you can see below it's sorting alphabetically.

---Model:

class Tag(models.Model):
        name = models.CharField(max_length=48, unique=True)
        data = models.ManyToManyField(Product)
        def __unicode__(self):
                return self.name

---Admin:

class TagAdmin(admin.ModelAdmin):
        pass
admin.site.register(Tag, TagAdmin)

Upvotes: 0

Views: 4305

Answers (2)

Blairg23
Blairg23

Reputation: 12045

As long as the data M2M points to a model that has a date field to order by, you can easily sort in your admin.py relevant Admin class. In this case, your model is Product, so if Product has a date field, you can use it to order the admin changelist.

Let's say your Admin class is the following:

@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ['name', 'data']
    ordering = ['data__date_field_name']

The line ordering = ['data__date_field_name'] will order by the data object's date_field_name field. date_field_name can be w/e the field is actually called that represents the data object's date field. Alphabetically or numerically will be depending on the field. Uses the field's normal ordering method. You can also do ordering = ['-data__date_field_name'] which will sort in descending order.

Source: https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.ordering

Upvotes: 1

You can override the queryset used for an m2m field via formfield_for_manytomany

class TagAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "data":
            kwargs["queryset"] = Product.objects.order_by('date_created')
        return super(TagAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

If you would like a global, non admin specific ordering, you can override get_query_set in your model manager.

class MyManager(models.Manager):
    def get_query_set(self):
         return super(MyManager, self).get_query_set().order_by('date_created') 
         # this would affect any ordering using this model including admin.

Upvotes: 2

Related Questions