Django filter many to many field in admin?

前端 未结 3 1923
说谎
说谎 2020-12-30 20:39

I have three objects:

Thing
  some fields

Bucket
  things = models.ManyToManyField(Thing)

User
  buckets = models.ManyToManyField(Bucket)
  things = models         


        
相关标签:
3条回答
  • 2020-12-30 21:38

    It is possible with django-selectable or django-autocomplete-light.

    0 讨论(0)
  • 2020-12-30 21:40

    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)
    
    0 讨论(0)
  • 2020-12-30 21:44

    Read the docs:

    class BucketAdmin(admin.ModelAdmin):
        def formfield_for_foreignkey(self, db_field, request, **kwargs):
            if db_field.name == "things":
                 kwargs["queryset"] = Things.objects.filter(...)
            return super(BucketAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
    
    0 讨论(0)
提交回复
热议问题