filter foreignkey field in django admin

后端 未结 7 1327
感情败类
感情败类 2020-12-02 20:42

I have these models:

class Entity(models.Model):
       name=models.CharField(max_length=100)
      
class Theme(models.Model):
   name=models.CharField(max_l         


        
7条回答
  •  旧时难觅i
    2020-12-02 21:07

    A bit unrelated, but similar to this so I'll post this here.

    I was looking for a way to remove the NULL choice selection on a ModelForm foreignkey field. I first thought I could filter the queryset as is done in other answers here, but that didn't work.

    I found that I can filter the entry where the pk value is NULL like this in the get_form method:

    
    class CompanyAdmin(admin.ModelAdmin):
        def get_form(self, request, obj=None, **kwargs):
            form = super().get_form(request, obj, **kwargs)
            # remove null choice
            form.base_fields["theme"].choices = ((pk, display) for pk, display in form.base_fields["theme"].choices if pk)
            return form
    

提交回复
热议问题