Django: accessing the model instance from within ModelAdmin?

后端 未结 3 1030
情话喂你
情话喂你 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:06

    The above answer from Erwin Julius worked for me, except I found that the name "get_object" conflicts with a Django function so name the function "my_get_object".

    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.my_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 my_get_object(self, request, model):
            object_id = request.META['PATH_INFO'].strip('/').split('/')[-1]
            try:
                object_id = int(object_id)
            except ValueError:
                return None
            return model.objects.get(pk=object_id)
    

    It told me not to "respond" to others' answers, but I'm not allowed to "reply" yet, and I have been looking for this for a while so hope this will be helpful to others. I am also not allowed to upvote yet or I totally would!

提交回复
热议问题