使用Django和DRF基于param返回不同的ManyToMany对象



我正试图弄清楚实现这种行为的最佳方式是什么:

我有一个类型为";配方";,其相关模型";IngredientRecipe";是从";"产品";带有关于其";供应商";。配方可以具有";牛肉;作为一种成分,该成分由多个供应商提供。我想要获得的是一份配方,其成分列表与所选地点的供应商提供的成分相对应。

例如:

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

这将返回id=34的配方细节和配料列表,但来自id=1的位置。也就是说;牛肉;将是与位置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)

现在我正在使用ModelViewSets和ModelSerializer来渲染保存的对象。

事先非常感谢。

您可以在IngredientRecipe:的配方字段中选择related_name='ingredients'

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.

最新更新