Django: accessing the model instance from within ModelAdmin?

后端 未结 3 1029
情话喂你
情话喂你 2020-11-29 21:50

I\'ve got a model for Orders in a webshop application, with an auto-incrementing primary key and a foreign key to itself, since orders can be split into multiple orders, but

3条回答
  •  佛祖请我去吃肉
    2020-11-29 22:21

    I've modeled my inline class this way. It's a bit ugly on how it gets the parent form id to filter inline data, but it works. It filters units by company from the parent form.

    The original concept is explained here http://www.stereoplex.com/blog/filtering-dropdown-lists-in-the-django-admin

    class CompanyOccupationInline(admin.TabularInline):
    
        model = Occupation
        # max_num = 1
        extra = 0
        can_delete = False
        formset = RequiredInlineFormSet
    
        def formfield_for_dbfield(self, field, **kwargs):
    
            if field.name == 'unit':
                parent_company = self.get_object(kwargs['request'], Company)
                units = Unit.objects.filter(company=parent_company)
                return forms.ModelChoiceField(queryset=units)
            return super(CompanyOccupationInline, self).formfield_for_dbfield(field, **kwargs)
    
        def get_object(self, request, model):
            object_id = resolve(request.path).args[0]
            try:
                object_id = int(object_id)
            except ValueError:
                return None
            return model.objects.get(pk=object_id)
    

提交回复
热议问题