Я работаю в системе диспетчеризации мини-заказов (например, Uber Eats), и мне хотелось бы показать объект OrderItem внутри объекта Order . Как видите, Order - это FK в модели OrderItem .
Я попытался вставить serializers.RelatedField()
, а также OrderItemModelSerializer()
в orders / serializers / orders.py , но безуспешно. Конечно, я делаю что-то не так.
Это список Order , внутри него нет объекта OrderItem : (
[
{
"id": 3,
"user": 1,
"customer": 1,
"store": 2,
"paid": true,
"ordered": false,
"picked_up": false,
"deliveried": false,
"created": "2020-04-29T21:57:07.671934Z",
"updated": "2020-04-29T21:57:07.671996Z"
},
{
"id": 1,
"user": 1,
"customer": 1,
"store": 2,
"paid": true,
"ordered": false,
"picked_up": false,
"deliveried": false,
"created": "2020-04-29T18:43:56.394898Z",
"updated": "2020-04-29T18:43:56.394943Z"
}
Как бы вы решили эту проблему?
Код показан ниже:
orders / models / orders.py
class Order(models.Model):
'''Orders models.'''
user = models.ForeignKey(User, on_delete=models.CASCADE)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
store = models.ForeignKey(Store, on_delete=models.CASCADE)
paid = models.BooleanField(default=True) # not added payments yet
# Status
ordered= models.BooleanField(
'Order made',
default=False,
help_text='Set True when the Customer wants the order to be delivered.'
)
picked_up = models.BooleanField(
'picked up by the rider',
default=False,
help_text='Set True when the rider has picked up the order on the Store.'
)
deliveried = models.BooleanField(
'deliveried to customer',
default=False,
help_text='Set True when the Customer has received the order.'
)
# Stats
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return 'Order id: {} Store {} Username {}'.format(
self.id,
self.store.name,
self.user.username
)
orders / models / order_items.py
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items')
meal = models.ForeignKey(Meal, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
def __str__(self):
return 'Order Item id: {} name: {}'.format(
self.id,
self.meal.name
)
orders / serializers / orders.py
class OrderModelSerializer(serializers.ModelSerializer):
'''Order model serializer.'''
class Meta:
"""Meta class."""
model = Order
fields = (
'id',
'user',
'customer',
'store',
'paid',
'ordered',
'picked_up',
'deliveried',
'created',
'updated'
)
read_only_fields = (
'created',
'updated'
)
заказов / сериализаторов / order_items.py
class OrderItemModelSerializer(serializers.ModelSerializer):
'''Order items model serializer.'''
class Meta:
"""Meta class."""
model = OrderItem
fields = (
'id',
'order',
'meal',
'quantity'
)
read_only_fields = ('id',)