How can I filter a queryset inside the Admin page of an object that has a 
ManyToManyField relation with a manually defined through model?

Given models.py

class Foo(models.Model): 
    foo_field1 = models.CharField(max_length=50) 

class Main(models.Model): 
    main_field1 = models.CharField(max_length=50) 
    m2mfield = models.ManyToManyField(Foo, through="FooBar") 

class FooBar(models.Model): 
    main = models.ForeignKey(Main, on_delete=models.CASCADE) 
    foo = models.ForeignKey(Foo, on_delete=models.CASCADE) 
    new_field = models.CharField(max_length=50)

Inside admin.py 

class M2MInlineAdmin(admin.TabularInline): 
    model = Main.m2mfield.through 
    extra = 1 

class MainAdmin(admin.ModelAdmin): 
    inlines = [M2MInlineAdmin,] 
    ... 

    def formfield_for_manytomany(self, db_field, request, **kwargs): 
        print('called formfield_for_manytomany') 
        return super().formfield_for_manytomany(db_field, request, **kwargs) 

    def get_field_queryset(self, db, db_field, request): 
        print('called get_field_queryset') 
        return super().get_field_queryset(db, db_field, request)

I try to access both of these methods, but none of them are called if I 
specify a through table. However, they do get called if the ManyToMany 
relation is simply defined as like this:

class Main(models.Model):
    main_field1 = models.CharField(max_length=50)
    m2mfield = models.ManyToManyField(Foo)

Is there a method to filter the queryset when a through table is specified 
(while being able to access the request context)?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/50d710ad-e65f-4dd2-985e-3814d5d9efdb%40googlegroups.com.

Reply via email to