Я хочу получить user.id в фоновом режиме, когда пользователь создает адрес доставки и данные о продукте в моделях, и я получаю эту ошибку
ull value in column "ordered_by_id" violates not-null constraint
DETAIL: Failing row contains (66, 5051, tetsst, 2018-10-11, f, null).
Это означает, что user.id не добавляется в моделипо какой-то причине.
Мои модели.py
class Product(models.Model):
price = models.FloatField()
name = models.CharField(default='gift', max_length=512)
ordered_by = models.ForeignKey(User, null=False)
date = models.DateField(auto_now_add=True)
purchased = models.BooleanField(default=False)
def __str__(self):
return self.name
class Delivery(models.Model):
address = models.CharField(max_length=256)
city = models.CharField(max_length=128)
country = models.CharField(max_length=128)
zip_code = models.IntegerField() #gotta change that one to charfield
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'."
" Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=16, blank=False)
delivered = models.BooleanField(default=False)
product = models.ForeignKey(Product)
мои serializers.py
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = (
"name",
"price",
)
class ProductDeliverySerializer(serializers.ModelSerializer):
product = ProductSerializer()
class Meta:
model = Delivery
fields = (
"address",
"city",
"country",
"zip_code",
"phone_number",
"product",
)
def create(self, validated_data):
product_data = validated_data.pop('product')
print(validated_data, product_data)
product = Product.objects.create(**product_data)
delivery = Delivery.objects.create(product=product, **validated_data)
return delivery
Когда я печатаю / проверяю проверенные данные, это фактически показывает, что «форма» / POSTзавершить {'address': 'address here', 'city': 'City is here', 'country': 'Country is here', 'zip_code': 3333, 'phone_number': '+19991234567', 'ordered_by': <SimpleLazyObject: <User: testuser>>}
вывод для product_data OrderedDict([('name', 'tetsst'), ('price', 5051.0)])
my views.py
class ProductList(generics.ListCreateAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
def perform_create(self, serializer):
serializer.save(ordered_by=self.request.user)
class DeliveryList(generics.ListCreateAPIView):
queryset = Delivery.objects.all()
serializer_class = ProductDeliverySerializer
def perform_create(self, serializer):
serializer.save(ordered_by=self.request.user)