[Django]-How to use ManyToManyField with condition

1👍

In ModelAdmin you can use the formfield_for_manytomany to filter your data
You can see more details in docs

i.e:

class ShowroomAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "stock_car":
            kwargs["queryset"] = Car.objects.filter(status='ACTIVE')
        return super(ShowroomAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

2👍

Assuming that you wish to obtain all show rooms with active cars:

Showroom.objects.filter(stock_car__status='ACTIVE')

More information: Django documentation: Making queries

👤Wtower

Leave a comment