Filter property objects by other property in Django (Admin)

371 Views Asked by At

How can you filter a property by another property in the object (perhaps in the models) such that you don't have to add filtering to all places where objects are access. E.g: Django Admin, ViewSet in Rest Framework and so on. But obviously, that might not be possible...

I have the following models:

class Food(models.Model):
    # ...
    pass


class Weight(models.Model):
    # ...
    food = models.ForeignKey('Food')


class Ingredient(models.Model):
    food = models.ForeignKey(Food, null=False)
    amount = models.DecimalField(decimal_places=2, max_digits=5)
    weight = models.ForeignKey(Weight)
    note = models.CharField(max_length=200, null=True, blank=True)

I'd like to have the list of possible 'Weights' under Ingredient to show only the weights that contain the 'Food' I selected, instead of Weight.objects.all()

Any idea how to get there?

2

There are 2 best solutions below

0
On BEST ANSWER

Assuming you want to update things in the Django Admin, you would probably need to use Ajax when adding a new object since the Food is unknown until someone makes a selection. At that point you can have jQuery or something similar update the available options in the Weight widget.

There are ways to filter the available list on edit in Django, look at formfield_for_dbfield (which allows you to assign a Widget and then queryset), but you would need to set the object information first via get_form. This can get complex and would make things messy if someone came in to edit the object and changed the food selected. Then you would again need ajax to rewrite the available options.

Since your need is dynamic, I think an ajax widget might be your best bet.

2
On
Ingredient.weight_set.filter(food_name="apple")