[Answered ]-How to get element id with foreignkey in admin.py

1👍

Here’s an answer to a similar question that should do the trick: https://stackoverflow.com/a/61579287/9638991. For your use case it would look like this (untested code):


class PansionatAdmin(admin.ModelAdmin):
    .....
    fields = ('title', 'slug', 'category', 'tags')
    ....

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "tags" and hasattr(request, ‘pansion_obj’):
            kwargs["queryset"] = Tag.objects.filter(category=request.pansion_obj.category)
        return super().formfield_for_manytomany(db_field, request, **kwargs)

    def get_object(self, request, object_id, from_field=None):
        obj = super().get_object(request, object_id, from_field=from_field)
        # Cache object for use in formfield_for_manytomany
        request.pansion_obj = obj
        return obj
👤kimbo

Leave a comment