I have a Django model that looks like the code below. At the moment, when I am using django rest framework to create a new menu instance, the dish column contains options created by all users on the platform. How should I go about filtering the dish column so it only has options created by the user? Should I be doing it in the views or serializer?
Thank you for the response in advance.
class Dish(models.Model):
user = models.ForeignKey(
User, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=280)
description = models.CharField(max_length=280)
image = models.ImageField(upload_to='static/images/post_image',
default='static/images/post_image/default.jpg')
def __str__(self):
return f'{self.title}'
def get_image_url(self, obj):
return obj.image.url
class Menu(models.Model):
user = models.ForeignKey(
User, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=280)
description = models.CharField(max_length=280)
dish = models.ManyToManyField(Dish)
price = models.SmallIntegerField(
validators=[MinValueValidator(1), MaxValueValidator(10000)], default=None)
def __str__(self):
return f'{self.title}'
This is how I ended up doing it for those who have the same problems in the future.
class UserDishForeignKey(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
user = self.context['request'].user
return Dish.objects.filter(user=user)
class MenuCreateSerializer(serializers.ModelSerializer):
dish = UserDishForeignKey(many=True)
class Meta:
model = Menu
fields = ['title', 'description', 'dish', 'price', ]
read_only_fields = ['user', ]
def get_user(self, obj):
return str(obj.user.username)
Assuming that you have an user
object, you can get all dishes associated to that user
like this:
user.dish_set
If you want to find all menu's that are having particular menus by dish's owner. That can be done like
Menu.objects.filter(dish__user=user)
Placement of this depends on what you are trying to achieve. If you want to validate the input, placement should be in serializer
class UserDishForeignKey(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
user = self.context['request'].user
return Dish.objects.filter(user=user)
class MenuCreateSerializer(serializers.ModelSerializer):
dish = UserDishForeignKey(many=True)
class Meta:
model = Menu
fields = ['title', 'description', 'dish', 'price', ]
read_only_fields = ['user', ]
def get_user(self, obj):
return str(obj.user.username)
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.