Есть модели:
class City(models.Model):
name = models.CharField(max_length=50, default='')
def __str__(self):
return self.name
class Street(models.Model):
name = models.CharField(max_length=50)
city = models.ForeignKey(City, on_delete=models.CASCADE)
def __str__(self):
return f"{self.city}: {self.name}"
class Shop(models.Model):
name = models.CharField(max_length=50)
city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)
street = models.ForeignKey(Street, on_delete=models.SET_NULL, null=True)
house = models.SmallIntegerField()
opening_time = models.TimeField()
closing_time = models.TimeField()
def __str__(self):
return f"{self.name} по адрессу {self.street} - {self.house}. Работает с {self.opening_time} до {self.closing_time}"
Есть сериализаторы:
class CitySerializer(serializers.ModelSerializer):
class Meta:
model = City
fields = ['id', 'name']
class StreetSerializer(serializers.ModelSerializer):
city = serializers.StringRelatedField(many=False)
class Meta:
model = Street
fields = ['id', 'name', 'city']
class ShopSerializer(serializers.ModelSerializer):
city = CitySerializer(read_only=True)
street = StreetSerializer(read_only=True)
class Meta:
model = Shop
fields = ['id', 'name', 'city', 'street', 'house', 'opening_time', 'closing_time']
Имеется такое вью:
class ShopView(APIView):
def post(self, request):
shop = request.data.get('shop')
serializer = ShopSerializer(data=shop)
if serializer.is_valid(raise_exception=True):
shop_saved = serializer.save()
return Response({"success": "Shop '{}' created successfully".format(shop_saved.name)})
def get(self, request):
shops = Shop.objects.all()
serializer = ShopSerializer(shops, many=True)
return Response({"shops": serializer.data})
При POST запросе в Postman следующего вида:
{"shop": {
"id": 1,
"name": "Globus",
"city": {"name":"Ryazan"},
"street": {"name": "Lenina", "city": {"name":"Ryazan"}},
"house": 2,
"opening_time": "8:00",
"closing_time": "22:00"
}
}
Соответствующие поля street и city равно null
{"id":2,
"name":"Globus2",
"city":null,
"street":null,
"house":2,
"opening_time":"08:00:00",
"closing_time":"22:00:00"
}]}
Не понимаю, почему сериализатор не отрабатывает?