我hava DRF设置在json中接收数据并将其存储在django中。序列化器正在关注
class ReservationSerializer(serializers.ModelSerializer):
room = RoomSerializer()
reserved_days = DaySerializer(many=True)
additional_services = AdditionalServicesSerializer(many=True)
class Meta:
model = Reservation
fields = [
'start',
'end',
'check_in_time',
'check_out_time',
'reserved_days',
'additional_services',
'room',
'has_refund',
'payed',
'guest_name',
'reservation_number',
]
我可以使用此序列化程序在json中准备模型,然后将此json与Requests
库一起发送吗?
答案 0 :(得分:1)
如果你看到了需要,它是可行的。虽然,JSON编码是在Response对象中完成的,它是一个完整的HTTPResponse子类,因此您需要对自己的数据进行编码:
import json
import requests
my_objects = Reservation.objects.all()
serializer = ReservationSerializer(data=my_objects, many=True)
if serializer.is_valid():
# now you do your encoding:
encoded_data = json.dumps(serializer.data)
response = requests.post(your_url,
headers={'Content-Type': 'application/json'},
data=encoded_data)