0

I'm trying to figure out if what's the best way to implement this behavior:

I have an object of type "Recipe", whose related model "IngredientRecipe" is obtained from a list of "Products" with information about its "Supplier". A recipe may have "beef" as an ingredient and this ingredient is supplied by several suppliers. What I want to obtain is a recipe whose list of ingredients corresponds to the ingredients supplied by the suppliers of the selected location.

For example:

https://api.url/recipes/34/?location=1

This would return the detail of the recipe with id=34 and the list of ingredients but from the location with id=1. That is, the price of the ingredient "beef" will be the one corresponding to the supplier of the location id=1.

models.py:

class Recipe(models.Model):
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='user_recipes')
    title = models.CharField(_('Recipe title'), max_length=255, blank=True)


class IngredientRecipe(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='products')
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients')
    quantity = models.FloatField(_('Quantity'))


class Product(models.Model):
    name = models.CharField(_('Name'), max_length=255)
    price = models.FloatField(_('Sale price'), default=0)
    supplier = models.ForeignKey(Supplier, blank=True, null=True, related_name='supplier_products',
                                 on_delete=models.CASCADE)


class Supplier(models.Model):
    name = models.CharField(_('Name'), max_length=255)
    location = models.ForeignKey(Location, on_delete=models.CASCADE)

Right now I'm using ModelViewSets and ModelSerializers to render saving my objects.

Thank you very much in advance.

1 Answers1

0

You can related_name='ingredients' on recipe field of IngredientRecipe:

def your_view_name(request, recipie_id):
    data = request.query_params # to take the location id query parameter
    data._mutable = True # dictionary from frontend immutable sometimes
    location_id = data.location
    recipie_list = Recipe.objects.filter(ingredients__product__supplier__location__id=location_id) # will get the recipie queryset based on the location.
Siva Sankar
  • 1,672
  • 1
  • 9
  • 16