Search code examples
djangoselectadminchained

about cacade foreignkey in django admin page


My model is like below:

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

class Phones(models.Model):
    manufacturer = models.ForeignKey(Manufacturers)
    name = models.CharField()

class Prices(models.Model):
    phone = models.ForeignKey(Phones)
    price = models.DecimalFeild()

and I have registered them in the admin.py

My problem is: In django's admin interface, When I add a price, I can select a phone from the dropdown list, But there are so many phones, So I want to select the manufacturer at first, then select the phone from the manufacturer's phones. How can I make this. Thanks very much.


Solution

  • The term for this is "chained select menus".

    There are a number of implementations in django. One that you may find useful is django-smart-selects.

    Using django-smart-selects, this is how you would write up your models:

    class Manufacturers(models.Model):
        name = models.CharField()
    
    class Phones(models.Model):
        manufacturer = models.ForeignKey(Manufacturers)
        name = models.CharField()
    
    class Prices(models.Model):
        phone = ChainedForeignKey(
            Phone, 
            chained_field="manufacturer",
            chained_model_field="manufacturer", 
            show_all=False, 
            auto_choose=True
        )
        price = models.DecimalField()
    

    All that said, I wonder if you are implementing this in the best fashion.

    It might be better to have Prices show up under the admin form for each phone. So instead of creating a price record and choosing the phone from a drop-down, you'd go into the record for that phone and add a price record. See django's documentation on InlineModelAdmin.