Answer the question
In order to leave comments, you need to log in
When creating an object through the Django Rest Framework, how to specify the associated field by the specified field?
There are models, serializers and views:
#models.py
class SKU(models.Model):
customer_uid = models.CharField("ID по данным клиента", max_length=100, blank = True)
name = models.CharField("Название", max_length=50)
def __str__(self):
return self.good.name + ' / '+ self.name
class Stocks(models.Model):
sku = models.ForeignKey(SKU, verbose_name="SKU", on_delete=models.PROTECT)
quantity = models.IntegerField("Фактический остаток")
reserved = models.IntegerField("В резерве")
#serializators.py
class SKUSerializer(serializers.ModelSerializer):
class Meta:
model = SKU
fields=['id', 'name', 'customer_uid']
read_only_fields = ['id']
class StocksSerializer(serializers.ModelSerializer):
sku_customer_uid = serializers.CharField(source="sku.customer_uid", read_only=True)
class Meta:
model = Stocks
fields = ['warehouse', 'sku_customer_uid', 'quantity', 'reserved', 'customer_company']
#views.py
class StocksView(CreateListMixin, viewsets.ModelViewSet):
queryset = Stocks.objects.all()
serializer_class = StocksSerializer
{
"warehouse": 1,
"sku_customer_uid": "4217-2000000002637",
"quantity": 2,
"reserved": 0,
"customer_company": 1
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question