I have a ManyToMany relationship between
Product. If I request Recipes, I am able to query also the relating products, but when I request Product, there is no related model data.
I think this is because the relationship is defined on the Recipe model. How can I query the Recipes related to Product (with the
through model info!)? Basically what I want is to query a product and see all recipes that need this product.
class Recipe(models.Model): ... products_input = models.ManyToManyField(Product, through='RecipeInput', related_name='products_input') ... class Product(models.Model): ... class RecipeInput(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.IntegerField() ...
class RecipeInputSerializer(serializers.HyperlinkedModelSerializer): product_key = serializers.ReadOnlyField(source='product.key') product_name = serializers.ReadOnlyField(source='product.name') class Meta: model = RecipeInput fields = ("product_name", 'amount', 'product_key', ) class RecipeSerializer(serializers.ModelSerializer): products_in = RecipeInputSerializer(source='recipeinput_set', many=True) class Meta: model = Recipe fields = "__all__" depth = 3 class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = "__all__" depth = 3