Django создание объекта с помощью вложенного сериализатора и модели
Здравствуйте, я пытаюсь создать 3 объекта модели в одном запросе из flutter в django restframework, но я не знаю, как использовать сериализатор для создания объекта, поэтому я реализовал много строк кода, чтобы сделать это, но он работает нормально. Это правильно или нет
View.py
from rest_framework.views import APIView
from .models import Booking, FromAddress, Product, ToAddress
from .serializers import BookingSerializer, FromAddressSerializer
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
class BookingView(APIView):
def get(self,req):
bookings = Booking.objects.all()
serializer = BookingSerializer(bookings,many=True)
return Response(serializer.data)
def post(self,req):
user = self.request.user
fromAddressData = req.data['from_address']
toAddressData = req.data['to_address']
productData = req.data['product']
from_address = FromAddress.objects.create(name=fromAddressData['name'],phone=fromAddressData['phone'],address=fromAddressData['address'],)
to_address = ToAddress.objects.create(name=toAddressData['name'],phone=toAddressData['phone'],address=toAddressData['address'],pincode=toAddressData['pincode'],)
product = Product.objects.create(title = productData['title'],weight = productData['weight'],nature_of_content=productData['nature_of_content'],breakable=productData['breakable'],)
from_address.save()
fadrs = FromAddress.objects.get(id= from_address.id)
print(FromAddressSerializer(fadrs))
to_address.save()
product.save()
booking = Booking.objects.create(user=req.user,from_address=fadrs,to_address=to_address,product= product, price=req.data['price'],
payment_id=req.data['payment_id'])
booking.save()
return Response('Success')
Model.py
from django.db import models
from django.contrib.auth.models import User
import uuid
# Create your models here.
class FromAddress(models.Model):
name = models.CharField(max_length=50)
phone = models.CharField(max_length=10)
address = models.TextField(max_length=200)
def __str__(self):
return self.name
class ToAddress(models.Model):
name = models.CharField(max_length=50)
phone = models.CharField(max_length=10)
address = models.TextField(max_length=200)
pincode = models.CharField(max_length=6)
def __str__(self):
return self.name
class Product(models.Model):
title = models.CharField(max_length=50)
weight = models.DecimalField(max_digits=5,decimal_places=2)
nature_of_content = models.CharField(blank=True,null=True,max_length=100)
breakable = models.BooleanField(default=False)
def __str__(self):
return f'{self.title} : {self.weight}'
class Booking(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE)
from_address = models.ForeignKey(FromAddress,on_delete=models.CASCADE)
to_address = models.ForeignKey(ToAddress,on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
tracking_number = models.CharField(unique=True,default=uuid.uuid4().hex[:12].upper(),max_length=15,verbose_name='Tracking Number',editable=False)
price = models.DecimalField(max_digits=6,decimal_places=2,)
payment_id = models.CharField(max_length=50)
booking_date = models.DateField(auto_now_add=True)
status = models.CharField(default='Booked',max_length=50)
def __str__(self):
return f'{self.user} {self.tracking_number}'
Serializer.py
from rest_framework import serializers
from .models import FromAddress,ToAddress,Product,Booking
class FromAddressSerializer(serializers.ModelSerializer):
class Meta:
model = FromAddress
fields = "__all__"
class ToAddressSerializer(serializers.ModelSerializer):
class Meta:
model = ToAddress
fields = "__all__"
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = "__all__"
class BookingSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(
read_only=True, default=serializers.CurrentUserDefault())
from_address = FromAddressSerializer(read_only = True)
to_address = ToAddressSerializer(read_only=True)
product = ProductSerializer(read_only= True)
class Meta:
model = Booking
fields = "__all__"
# depth = 1
**Это запрос API от Flutter **
Future newCourier(Booking booking) async {
try {
print('Clicked');
var response = await http.post(Uri.parse(courierBooking),
headers: {
"Authorization": 'Bearer ${box.read('access')}',
"Content-Type": "application/json",
},
body:json.encode( booking.toJson() ));
print(response.body);
} catch (e) {}
}
class FromAddress {
FromAddress({
required this.id,
required this.name,
required this.phone,
required this.address,
});
int id;
String name,
phone,
address;
factory FromAddress.fromJson(Map<String, dynamic> json) => FromAddress(
id: json["id"],
name: json["name"],
phone: json["phone"],
address: json["address"],
);
Map<String, dynamic> toJson() => {
"name": name,
"phone": phone,
"address": address,
};
}
Flutter To Address Model
class ToAddress {
ToAddress({
required this.id,
required this.name,
required this.phone,
required this.address,
required this.pincode,
});
int id;
String name, phone, address, pincode;
factory ToAddress.fromJson(Map<String, dynamic> json) => ToAddress(
id: json["id"],
name: json["name"],
phone: json["phone"],
address: json["address"],
pincode: json["pincode"],
);
Map<String, dynamic> toJson() => {
"name": name,
"phone": phone,
"address": address,
"pincode": pincode,
};
}
Модель продукта
class Product {
Product({
required this.id,
required this.title,
required this.weight,
required this.natureOfContent,
required this.breakable,
});
int id;
String title, weight, natureOfContent;
bool breakable;
factory Product.fromJson(Map<String, dynamic> json) => Product(
id: json["id"],
title: json["title"],
weight: json["weight"],
natureOfContent: json["nature_of_content"],
breakable: json["breakable"],
);
Map<String, dynamic> toJson() => {
"title": title,
"weight": weight,
"nature_of_content": natureOfContent,
"breakable": breakable,
};
}
Окончательное объединение данных в одну модель Модель бронирования
import 'fromaddress.dart';
import 'toaddress.dart';
import 'product.dart';
class Booking {
Booking({
required this.id,
required this.fromAddress,
required this.toAddress,
required this.product,
required this.trackingNumber,
required this.price,
required this.paymentId,
required this.bookingDate,
required this.status,
required this.user,
});
int id;
FromAddress fromAddress;
ToAddress toAddress;
Product product;
String trackingNumber;
String price;
String paymentId;
DateTime bookingDate;
String status;
int user;
factory Booking.fromJson(Map<String, dynamic> json) => Booking(
id: json["id"],
fromAddress: FromAddress.fromJson(json["from_address"]),
toAddress: ToAddress.fromJson(json["to_address"]),
product: Product.fromJson(json["product"]),
trackingNumber: json["tracking_number"],
price: json["price"],
paymentId: json["payment_id"],
bookingDate: DateTime.parse(json["booking_date"]),
status: json["status"],
user: json["user"],
);
Map<String, dynamic> toJson() => {
"from_address": fromAddress.toJson(),
"to_address": toAddress.toJson(),
"product": product.toJson(),
// "tracking_number": trackingNumber,
"price": price,
"payment_id": paymentId,
// "booking_date": "${bookingDate.year.toString().padLeft(4, '0')}-${bookingDate.month.toString().padLeft(2, '0')}-${bookingDate.day.toString().padLeft(2, '0')}",
};
}