django ForeignKey field should only select by category

Viewed 63

I have a ForeignKey field in my model and in Django admin and Django forms` when I display that field or in Django admin, I get all the field that in that model However, I only want to display selected fields in that dropdown, for example

class Area(models.Model):
    area_type_options = (('cc', 'Cost Center'), ('pc', 'Profit Center'),)
    name = models.CharField(max_length=100)
    area_type = models.CharField(max_length=100, choices=area_type_options)


class Item(models.Model):
    name = models.CharField(max_length=150, null=True, unique=True)
    profit_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='profit_center')
    cost_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='cost_center')

I get to see all the records in the cost_center and all the records in the profit_center however I only want to see where area_type is cc to cost_center and where area type pc to profit_center

Please Help

1 Answers

You can use ForeignKey.limit_choices_to [Django docs] to do this:

class Item(models.Model):
    name = models.CharField(max_length=150, null=True, unique=True)
    profit_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='profit_center', limit_choices_to={'area_type': 'pc'})
    cost_center = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE, related_name='cost_center', limit_choices_to={'area_type': 'cc')
Related