IntegrityError at /create_invoice NOT NULL constraint failed: invoiceAPI_invoice.buyer_id
Я пытаюсь создать счет-фактуру, который имеет два внешних ключа seller и buyer и одно поле many to many to для items. Я создал сериализатор для продавца, покупателя и товаров и вложенный сериализатор для счета-фактуры, и когда я создаю счет-фактуру, я получаю ошибку IntegrityError at /create_invoice NOT NULL constraint failed: invoiceAPI_invoice.buyer_id. В данных, которые я передал, нет id. Так как я не хочу передавать id через JSON, возможно ли, чтобы Django создал первичный ключ для всех моделей.
Это мой файл serializers.py
class SellerSerializer(serializers.ModelSerializer):
class Meta:
model = Seller
fields = ('__all__')
class BuyerSerializer(serializers.ModelSerializer):
class Meta:
model = Buyer
fields = ('__all__')
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('name', 'price', 'quantity', 'tax')
class InvoiceSerializer(serializers.ModelSerializer):
seller = SellerSerializer(many=False, read_only=True)
buyer = BuyerSerializer(many=False, read_only=True)
items = ItemSerializer(many=True, read_only=True)
class Meta:
model = Invoice
fields = ('seller', 'buyer', 'items', 'date')
def create(self, validated_data):
seller_data = validated_data.pop('seller')
buyer_data = validated_data.pop('buyer')
items_data = validated_data.pop('items')
seller = Seller.objects.create(**seller_data)
buyer = Buyer.objects.create(**buyer_data)
items = []
for item_data in items_data:
items.append(Item.objects.create(**item_data))
invoice = Invoice.objects.create(seller=seller, buyer = buyer, item=items)
return invoice```
This is the models.py file.
**models.py**
```
class Seller(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
phone = models.CharField(max_length=12)
address = models.CharField(max_length=200)
def __str__(self):
return self.name
class Buyer(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
phone = models.CharField(max_length=12)
address = models.CharField(max_length=200)
def __str__(self):
return self.name
class Item(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
price = models.DecimalField(decimal_places=2, max_digits=20)
quantity = models.IntegerField(default=1)
tax = models.DecimalField(decimal_places=2, max_digits=4)
def total(self):
total = Decimal(str((self.price-self.tax)*self.quantity))
return total.quantize(Decimal('0.01'))
def __str__(self):
return f'{self.name} {self.quantity}'
class Invoice(models.Model):
id = models.AutoField(primary_key=True)
seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
buyer = models.ForeignKey(Buyer, on_delete=models.CASCADE)
item = models.ManyToManyField(Item)
date = models.DateTimeField(auto_now_add=True)```