程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用 Django 和 DRF 基于参数返回不同的 ManyToMany 对象大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用 Django 和 DRF 基于参数返回不同的 ManyToMany 对象?

开发过程中遇到使用 Django 和 DRF 基于参数返回不同的 ManyToMany 对象的问题如何解决?下面主要结合日常开发的经验,给出你关于使用 Django 和 DRF 基于参数返回不同的 ManyToMany 对象的解决方法建议,希望对你解决使用 Django 和 DRF 基于参数返回不同的 ManyToMany 对象有所启发或帮助;

我正在尝试找出实现此行为的最佳方法:

我有一个“Recipe”类型的对象,其相关模型“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,related_name='products')
    recipe = models.ForeignKey(Recipe,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,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 和 ModelSerializers 来渲染保存我的对象。

非常感谢您。

解决方法

您可以在 related_name='ingredients' 的配方字段上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.

大佬总结

以上是大佬教程为你收集整理的使用 Django 和 DRF 基于参数返回不同的 ManyToMany 对象全部内容,希望文章能够帮你解决使用 Django 和 DRF 基于参数返回不同的 ManyToMany 对象所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:对象