filter foreignkey field in django admin

后端 未结 7 1323
感情败类
感情败类 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条回答
  •  半阙折子戏
    2020-12-02 21:03

    Another option is to create a custom model form where the queryset attribute of the theme field will be fine tuned to meet your needs.

    class CompanyForm(ModelForm):
        class Meta:
            model = CompanyForm
            fields = __all__ # or a tuple of fields
    
        def __init__(self, *args, **kwargs):
            super(CompanyForm, self).__init__(*args, **kwargs)
            if self.instance: # Editing and existing instance
                self.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
    

    This model form can be also reused outside of the django admin area.

提交回复
热议问题