Passing model instances by id in serializer Django Rest Framework

django serializer
django rest framework serializer queryset
django rest framework nested serializer
django rest framework nested serializer post
django rest framework exclude fields
django rest framework many to many
drf serializer validate
django serializer example

When I post product_id in postman I am getting this result

    "id": 13,
    "user": 26,
    "product": null,
    "quantity": 1

which product is null, but I do not want this.

my serializer looks like this

class CartSerializer(serializers.ModelSerializer):

    product = ProductSerializer(required=False)

    class Meta:
        model = Cart
        fields = ['id', 'user', 'product', 'quantity']

    def create(self, validated_data):
        return Cart.objects.create(**validated_data)

I add product to cart from admin I get this

            "id": 7,
            "user": 26,
            "product": {
                "id": 8,
                "name": "Apple Watch 4 series",
                "brand": "Apple",
                "color": {
                    "id": 1,
                    "color": "Black"
                "price": "250.00",
                "discount": 2,
                "images": [
                        "id": 6,
                        "product": 8,
                        "image": "http://localhost:8000/media/products/2019/12/09/b_Amazfit_Bip.jpg"
                "slug": "apple-watch-4-series"
            "quantity": 1

that is exactly what I want but I cannot override serializer method. How can I do this? If I post product id I should get the result above shown. Thanks inadvance!

you can create the custom serializer field

class CustomForeignKeyField(serializers.PrimaryKeyRelatedField):

    def get_queryset(self):
        return self.queryset

    def to_representation(self, value):
        value = super().to_representation(value)
        product = Product.objects.get(pk=value)
        return ProductSerializer(product).data

in serializer

class CartSerializer(serializers.ModelSerializer):

    product = CustomForeignKeyField(required=False, queryset=Prouct.objects.all() )

    class Meta:
        model = Cart
        fields = ['id', 'user', 'product', 'quantity']

    def create(self, validated_data):
        return Cart.objects.create(**validated_data)

it will accept product as int value and return json value in response. It can make generic for other. if you pass serilizer name also in constructor.

Serializers, This tutorial will cover creating a simple pastebin code highlighting Web API. We can also serialize querysets instead of model instances. ModelSerializer): class Meta: model = Snippet fields = ['id', 'title', 'code', 'linenos', 'language', 'style']. id field in django rest framework serializer. Ask Question Asked 7 years, 4 months ago. Active 4 months ago. Django REST framework: non-model serializer. 5.

As of DRF 3.2.4, so long as you add


to the models field like so:

class Posts(models.Model):
    country = models.ForeignKey(Country, blank=True)

then DRF will treat the field as optional when serializing and deserializing it (Note though that if there is no null=True on the model field, then Django will raise an error if you try to save an object to the database without providing the field).

See the answer here for more information:

DjangoRestFramework - correct way to add "required = false" to a ModelSerializer field?

If you are using pre-DRF 3.2.4, then you can override the field in the serializer and add required=False to it. See the documentation here for more information on specifying or overriding fields explicitily:

So something like this (Note that I did not fully test the code below but it should be something along these lines):

class PostsSerializer(serializers.ModelSerializer):
    country = serializers.PrimaryKeyRelatedField(required=False)
    class Meta:
        model = Posts
        fields = ('user', 'post', 'country',)

        def create(self, validated_data):
            return Posts.objects.create(**validated_data)

1 - Serialization, When using the ModelSerializer class, serializer fields and relationships will be print(repr(serializer)) AccountSerializer(): id = IntegerField(label='ID', queryset - The queryset used for model instance lookups when validating the field input. so we don't need to pass them as arguments. view_name = 'customer-detail'� We will explore different ways to create a Django Rest Framework(DFR) API in a 3 part series starting with a plain APIView(PART 1) then using GenericAPIView(PART 2) and finally using ViewSets(PART 3).

Add ProductSerializer inside many = True class CartSerializer(serializers.ModelSerializer):

    product = ProductSerializer(required=False,many=True)

    class Meta:
        model = Cart
        fields = ['id', 'user', 'product', 'quantity']

    def create(self, validated_data):
        return Cart.objects.create(**validated_data)

Serializer relations, Django, API, REST, Serializers, ModelSerializer, HyperlinkedModelSerializer, Serializers allow complex data such as querysets and model instances to be By default, serializers must be passed values for all required fields or they will Capitalizing the titles of the books queryset = Book.objects.all() data = [ {'id': 3,� Tutorial 1: Serialization Introduction. This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.

In Django, any foreign key is saved with _id appended as post fix to the field name you have declared. But when you are sending some data to some API, you should use it without _id post fix. You should use product from postman. Serializer only get field which are declared in serializer Meta class. As your product field is optional, your serializer is not giving any error. So that is why you are getting product as null in your response. If you want to send data in product_id field instead of product field, you should change your serializer like this.

class CartSerializer(serializers.ModelSerializer):

    product_id = serializer.IntegerField(required=False)

    class Meta:
        model = Cart
        fields = ['id', 'user', 'product_id', 'quantity']

    def create(self, validated_data):
        return Cart.objects.create(**validated_data)

    def to_representation(self, validated_data):
        data = super().to_representation(validated_data)
        data.update({'product': ProductSerializer(instance.product).data})
        return data

Serializers - Django REST framework, In general, I feel like the DRF documentation is not explicit enough about what I see id is from the request URL instance = Thing.objects.get(id=id) serializer do pass just the PK of the model object to use the serializer as-is, and this works:. I am using Django rest framework 2.3 I have a class like this class Quiz(): fields.. # A custom manager for result objects class SavedOnceManager(models.Manager):

Django REST Framework, The 3.0 release of Django REST framework is the result of almost four years of Also you can't set extra attributes on the instance directly, but instead pass them to ModelSerializer): class Meta: model = MyModel fields = ('id', 'email', 'notes',� The django-rest-framework-gis package provides geographic addons for django rest framework like a GeometryField field and a GeoJSON serializer. django-rest-framework-hstore The django-rest-framework-hstore package provides an HStoreField to support django-hstore DictionaryField model field.

3.0 Announcement - Django REST framework, Django's serialization framework provides a mechanism for “translating” Django fully serialize your Restaurant instances, you will need to serialize the Place models as well: Be aware that not all Django output can be passed unmodified to json . An integer id isn't always the most convenient way to refer to an object; � Django, API, REST, 2 - Requests and responses. Tutorial 2: Requests and Responses. From this point we're going to really start covering the core of REST framework.

Serializing Django objects | Django documentation, To simulate this pattern using a Django REST Framework serializer you can do You can also pass several parameters at once: from django.contrib.auth. models import User from django.db import models class Invoice(models. queryset = Invoice.objects.all() serializer_class = InvoiceSerializer def� Django, API, REST, Serializer relations. Note: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the lookup_field and lookup_url_kwarg arguments.

  • What you mean by you cannot override serializer method? Is there any problem?
  • Sorry i meant that i want to get desired result above shown
  • How can you return the product information if product is null?
  • @Nerd as @JPG said you should pass the product_id
  • If post {'product': 8} in the postman it should return all details but I cannot do this how can I do?
  • it returns the same { "id": 26, "quantity": 1, "product": 8, "user": 26 }
  • what can I do to return product details?
  • You add depth=2 in class serializer in below the fields
  • i added but it return user information not product information why is that?