Reputation: 613
I have 3 django models like this
To keep record of orders
class Orders(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, blank=True, null=True)
total_amount = models.DecimalField(max_digits=10, decimal_places=2)
which articles are in order like pizza etc
class OrderArticle(models.Model):
order = models.ForeignKey(Orders, on_delete=models.CASCADE)
article = models.ForeignKey(Articles, on_delete=models.CASCADE)
Article options of articles in order (like topping on pizza , now topping can be 4 or more types)
class OrderArticleOptions(models.Model):
article_option = models.ForeignKey(ArticlesOptions, on_delete=models.CASCADE)
order_article = models.ForeignKey(OrderArticle, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
price = models.DecimalField(max_digits=10, decimal_places=2)
To keep track of this multipul type of Article options I made this table . So example will be . Customer purchased a pizza with 2 toppings , 1st topping fajita quantiity is 1 and 2nd topping oliva quantity is 3 .
to get this use case using Django Rest framework what should I do ?
Issue
I want data like this
data {
orders[
article1
{
articleoptio1
{}
articleoption2
{}
}
]
}
Now issue is when I add 2 type of toppings to a single article in order, it creates 2 diff orders with 2 articles with each article option. While I want 1 article with 2 article options .
Upvotes: 0
Views: 417
Reputation: 111
class ArticlesSerializer(ModelSerializer):
class Meta:
model = Articles
fields = "__all__"
class OrderSerializer(ModelSerializer):
articles = ArticlesSerializer(source="resturant.article", many=True)
class Meta:
model = Orders
fields = "__all__"
Ok here I am using nested serializer, with key, "source". "source" is a little bit advanced concept I am sorry for using that, but I can't see any other optimal way. You can call the serializer from your views.
If you want to see learn more about nested serializers, I recommend you see the tutorial,
https://www.youtube.com/watch?v=rAJAC_P52VU
Upvotes: 1
Reputation: 111
Try Nested Serializers, It will solve your problem. See the nested serializer docs.
https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
Upvotes: 0