How to limit choice field options based on another choice field in django admin

前端 未结 3 585
盖世英雄少女心
盖世英雄少女心 2020-12-05 00:57

I have the following models:

class Category(models.Model):
    name = models.CharField(max_length=40)

class Item(models.Model):
    name = models.CharField(         


        
3条回答
  •  不知归路
    2020-12-05 01:58

    There is django-smart-selects:

    If you have the following model:

    class Location(models.Model)
        continent = models.ForeignKey(Continent)
        country = models.ForeignKey(Country)
        area = models.ForeignKey(Area)
        city = models.CharField(max_length=50)
        street = models.CharField(max_length=100)
    

    And you want that if you select a continent only the countries are available that are located on this continent and the same for areas you can do the following:

    from smart_selects.db_fields import ChainedForeignKey 
    
    class Location(models.Model)
        continent = models.ForeignKey(Continent)
        country = ChainedForeignKey(
            Country, 
            chained_field="continent",
            chained_model_field="continent", 
            show_all=False, 
            auto_choose=True
        )
        area = ChainedForeignKey(Area, chained_field="country", chained_model_field="country")
        city = models.CharField(max_length=50)
        street = models.CharField(max_length=100)
    

提交回复
热议问题