Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter many to many field in admin?

I have three objects:

Thing   some fields  Bucket   things = models.ManyToManyField(Thing)  User   buckets = models.ManyToManyField(Bucket)   things = models.ManyToManyField(Thing) 

When editing my "Bucket" field in the admin, I want to be able to select Things, but only those things that are in the "Things" list on the user currently logged in.

How can I do that? In other words, how can I filter the list of Things in the Bucket admin?

Thank you very much for your help in advance.

like image 280
Andrew Avatar asked Aug 29 '12 02:08

Andrew


People also ask

How take data from many to many field in Django?

A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.

Can you filter by property Django?

Django-property-filter is an extension to django-filter and provides functionality to filter querysets by class properties. It does so by providing sub-classes for Filters and Filtersets to keep existing django-filter functionality. For more details and examples check the documentation.


1 Answers

There is a formfield_for_manytomany. Usage is similar to the answer given by defuz.

ModelAdmin.formfield_for_manytomany(db_field, request, **kwargs)¶ 

Like the formfield_for_foreignkey method, the formfield_for_manytomany method can be overridden to change the default formfield for a many to many field. For example, if an owner can own multiple cars and cars can belong to multiple owners – a many to many relationship – you could filter the Car foreign key field to only display the cars owned by the User:

class MyModelAdmin(admin.ModelAdmin):     def formfield_for_manytomany(self, db_field, request, **kwargs):         if db_field.name == "cars":             kwargs["queryset"] = Car.objects.filter(owner=request.user)         return super(MyModelAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) 
like image 103
arunkumar Avatar answered Sep 20 '22 01:09

arunkumar