R
R
raxer2021-02-26 12:46:21
Django
raxer, 2021-02-26 12:46:21

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


Through Get I receive such answer.
{
            "warehouse": 1,
            "sku_customer_uid": "4217-2000000002637",
            "quantity": 2,
            "reserved": 0,
            "customer_company": 1
        }


But I can't figure out how to create a record with a link to the SKU object via a POST request, specifying "sku_customer_uid" (i.e. instead of the SKU ID, I need to specify its customer_uid)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question