简体   繁体   中英

DRF - How to queryset to only objects that the user is the owner of within an intermediate model?

I'm my DRF API, I have an intermediate model Ingredient that links two models, Product and Recipe .

class Product(models.Model):
   name = models.CharField()
class Recipe(models.Model):
   name = models.CharField()
   user = models.ForeignKey(User, on_delete=models.CASCADE)
   ingredients = models.ManyToManyField(Product, through='ingredient')
class Ingredient(models.Model):
   product = models.ForeignKey(Product, on_delete=models.CASCADE)
   recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
   quantity = models.FloatField(default=0)

In my current DRF generics.CreateAPIView for Ingredient , I want it to only display and allow a user to see and send a post request to create a new Ingredient entry for a Recipe that they own. But right now it keeps displaying Recipes for all users.

I tried filtering the Recipe for the Ingredient model in my serializers.py with:

serializers.py:

class IngredientPostSerializer(serializers.ModelSerializer):
   recipes = serializers.SerializerMethodField()
   def get_recipes(self, obj):
        recipes = Recipe.objects.filter(user_id=self.request.user.id)
        return recipes
   class Meta:
      model = Ingredient
      fields = '__all__'

add the following function to the view that uses the IngredientPostSerializer

def get_queryset(self):
    current_user = self.request.user
    return self.queryset.prefetch_related(Prefetch('recipe', 
                               queryset=Recipe.objects.filter(user=current_user)))

please take a look at this question for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM