Django内联模型管理过滤器外部字段

时间:2013-08-19 00:18:18

标签: django django-models django-admin foreign-keys inline

我有以下问题。

我有3个型号:

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)

我想与Site&图片内联管理模型:

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


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


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

我想要做的是当我选择Site in Picture admin时,它只显示我属于我正在查看的当前交易的网站(如果我正在更新 - 不创建新的)。

我希望这可以在管理员工作,我花了很多时间搜索网页,但找不到任何有用的内容,请帮忙!

我试图这样做,但我不知道如何访问父模型实例来获取交易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)

2 个答案:

答案 0 :(得分:1)

在DTing的变体中,我看到了问题 - self.instance.deal在编辑模式下设置,但在添加模式时未设置

我想,你应该写

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

代替

答案 1 :(得分:0)

Django: accessing the model instance from within ModelAdmin?

class PictureInlineForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PictureInlineForm, self).__init__(*args, **kwargs)
        self.fields['site'].queryset = Site.objects.filter(
            deal=self.instance.deal)

class PictureInline(admin.ModelAdmin):
    form = PictureInlineForm