zHepHirotHz
zHepHirotHz

Reputation: 137

How to use ManyToManyField with condition

In django models I need to filtering ManyToManyField with some condition

STATUS_CHOICES=(
  ('ACTIVE', 'Active'),
  ('INACTIVE', 'Inactive'),)
  

class Car(models.Model):
    name = models.CharField()
    status = models.CharField(choices=STATUS_CHOICES,
                              default='ACTIVE')

class Showroom(models.Model):
    name = models.CharField()
    stock_car = models.ManyToManyField('Car')

This code is my attempt to get a list of all cars but I need to filter based on some condition.

I need ManyToManyField to contain only a car marked by

status = 'ACTIVE'

Any idea how to handle it or some sample code is appreciated.

Upvotes: 3

Views: 1861

Answers (2)

dfranca
dfranca

Reputation: 5322

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)

Upvotes: 1

Wtower
Wtower

Reputation: 19902

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

Upvotes: 2

Related Questions