Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Inline Model Admin filter Foreign Field

I have a following problem.

I have 3 models:

class Deal(models.Model):
    name = models.CharField(max_length=80)

class Site(models.Model):
    name = models.CharField(max_length=80)
    deal = models.ForeignKey(Deal)

class Picture(models.Model):
    title = models.CharField(max_length=80)
    deal = models.ForeignKey(Deal)
    site = models.ForeignKey(Site)

I want to make Deal Admin with Site & Picture inline admin models:

class SiteInline(admin.StackedInline):
    model = Site
    extra = 1


class PictureInline(admin.StackedInline):
    model = Picture
    extra = 1


class DealAdmin(admin.ModelAdmin):
    inlines = [
        SiteInline,
        PictureInline,
    ]

What I want to do is when I am selecting Site in Picture admin it shows only sites that I belong to the current Deal i am viewing (if im updating - not creating new one).

I want this to work in admin, I've spent many hours searching web but couldn't find anything useful, please help!

I was trying to do it this way, but I don't know how to access the parent model instance to get the deal id:

def formfield_for_foreignkey(self, db_field, request=None, **kwargs):

    if db_field.name == 'site':
        kwargs['queryset'] = Site.objects.filter(deal__id=1)

    return super(PictureInline, self).formfield_for_foreignkey(db_field, request=None, **kwargs)
like image 922
Byteme Avatar asked Nov 11 '22 23:11

Byteme


1 Answers

In DTing's variant I see the problem - self.instance.deal is setted in edit mode, but it unsetted in adding mode

I think, you should wrote

try:        
    self.fields['site'].queryset = Site.objects.filter(deal=self.instance.deal)
except:
    self.fields['site'].queryset = Site.objects

instead

like image 172
Y.N Avatar answered Dec 04 '22 00:12

Y.N