[Django]-Formatting inline many-to-many related models presented in django admin

0👍

Maybe it is not what you expect but I would introduce InvoiceItem model which would link Invoice to Product. So you would have 2x 1:n instead of m:n relation. Then use inline custom form for InvoiceItem and raw_id_fields in that form for Product choice.

In InvoiceItem form then you could add readonly fields that would display values you need to display. You will have to provide data for these fields in Form’s init reading them from InvoiceItem instance. Or you could also derive from raw_id_field widget and in render method of this widget append some additional data from the product model?

0👍

This is an old question, but I have related to it today.

You can find the answer here – https://blog.ionelmc.ro/2012/01/19/tweaks-for-making-django-admin-faster/

The code:

class MyAdmin(admin.TabularInline):
    fields = 'myfield',
    def formfield_for_dbfield(self, db_field, **kwargs):
        formfield = super(MyAdmin, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'myfield':
            # dirty trick so queryset is evaluated and cached in .choices
            formfield.choices = formfield.choices
        return formfield

This can cut your waiting times from anything like 5 minutes to around 15 seconds.

👤idik

Leave a comment