سؤال

I have a model with a property that I'd like to have the adminmodel ordered by.

class StoreAdmin(admin.ModelAdmin):
    list_display = ('user', 'total',)

admin.site.register(Store, StoreAdmin)

Model:

class Store(models.Model):
    user = models.ForeignKey(User, related_name="store")

    @property
    def total(self):
        num = 0
        for x in Coins.objects.all():
            num += x.value
        return num

How do you order the ModelAdmin by the total since it is a property? Thanks in advance for the help!

هل كانت مفيدة؟

المحلول

Give this link a shot, as it may have your answer. https://stackoverflow.com/a/8478586/1011998

In short, since the property you're trying to order by doesn't exist in SQL, then the SQL has to return all results and then order them by your property in Python instead. As you can imagine, this is significantly slower.

I'd suggest looking into storing the field "total" as a field in the database as a denormalized field (int) and simply update it whenever the user object is updated by overriding the save() method. That way you benefit from both the speed of not having to constantly and dynamically recalculate totals on the fly (that'll become SQL later when working with medium-big data), and the speed of MySQL indexing (always consider what your "where" and "order by" clauses are).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top