I am new to django. I had searched all over stackoverflow but did get anything related.
I had two Table Owner and Services. owner can select N no of services. I am using ManyToManyField and i want to fetch related values in Generic View. may be it can be achieved using prefetch_related function but i dont know how. I want output like below. can anyone please help me achieving below expected output. Thanks
Expected Output
[
{
"owner_id": 1,
"first_name": "james",
"last_name": "cook",
"services_id": [
[1, service_title, desc],
[2, service_title, desc],
[3, service_title, desc]
]
}
]
model.py
class services(models.Model):
service_id=models.IntegerField(primary_key=True)
title=models.CharField(max_length=200)
description=models.TextField()
type=models.PositiveSmallIntegerField() #1: Package; 2: A La Carte
status=models.PositiveSmallIntegerField(default=1)
class reservations(models.Model):
owner_id=models.IntegerField()
first_name=models.CharField(max_length=50)
last_name=models.CharField(max_length=50)
services_id=models.ManyToManyField(services, related_name='services')
serializers.py
class servicesSerializer(ModelSerializer):
class Meta:
model=services
fields = [
'service_id'
'title',
'description',
'type',
]
class ownerSerializer(ModelSerializer):
class Meta:
model=reservations
fields = [
'owner_id',
'first_name',
'last_name',
'services_id',
]
View.py
class upcomingServices(ListAPIView):
queryset = owner.objects.all()
serializer_class=ownerSerializer
output
[
{
"owner_id": 1,
"first_name": "james",
"last_name": "cook",
"services_id": [
1,
2,
3
]
}
]
答案 0 :(得分:2)
在ServicesSerializer
class servicesSerailizer(ModelSerializer):
class Meta:
model=services
fields = [
'service_id'
'title',
'description',
'type',
]
def to_representation(self, value):
return [value.pk, value.title, value.description]
并将其添加到您的ownerSerializer
class ownerSerializer(reservationSerailizer):
service_id = servicesSerializer(many=True, read_only=True)
class Meta:
model=reservations
fields = [
'owner_id',
'first_name',
'last_name',
'services_id',
]
Here文档
答案 1 :(得分:1)
我稍微更改了view
,
class upcomingServices(ListAPIView):
queryset = reservations.objects.all() # Changed here
serializer_class = ownerSerializer
如下所示更改serializer.py
,
class servicesSerializer(serializers.ModelSerializer):
class Meta:
model = services
fields = ['service_id'
'title',
'description',
'type',
]
def to_representation(self, instance):
return [instance.service_id, instance.title, instance.description]
class ownerSerializer(serializers.ModelSerializer):
services_id = servicesSerializer(many=True)
class Meta:
model = reservations
fields = [
'owner_id',
'first_name',
'last_name',
'services_id',
]