Home > Blockchain >  How to get element id with foreignkey in admin.py
How to get element id with foreignkey in admin.py

Time:12-02

I have a question. Can i pass the data for filtering another field(manytomany) in admin.py ? I need to get linked foreignkey id value.

Models.py

class Pansions(models.Model):
......
    category = models.ForeignKey(Category, null=True, on_delete=models.PROTECT, related_name='cards', verbose_name='Category')
......

Admin.py

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

def formfield_for_manytomany(self, db_field, request, **kwargs):
   if db_field.name == "tags":
      kwargs["queryset"] = Tag.objects.filter(category__id = "GET ID FOREIGNKEY_FIELD (caterogy)")
   return super().formfield_for_manytomany(db_field, request, **kwargs)

I try to get data from models.py, but it not happen. Is it possible?

CodePudding user response:

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
  • Related