how to get reverse relation in django serializers SlugRelatedField












1















I have two models ProductTypeModel and ProductModel, product_type is the foreign key in the product. Then I wrote a ModelSerializer for a product to get all the entries of ProductModel and along with some additional info.
Now I'm unable to get product_sub_type from the ProductTypeModel in ProductSerializer



I have tried SlugRelatedField in serializers, tried to set slug_field=product_sub_type and slug_field=product_type__product_sub_type and slug_field=product_type.product_sub_type



models.py



class ProductType(models.Model):
"""Product type model."""

id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
hsn = models.ForeignKey(
HSN,
related_name='product_types',
on_delete=models.SET_NULL,
null=True, blank=True
)
product_type = models.CharField(max_length=255, null=True, blank=True)
product_sub_type = models.CharField(max_length=255, db_index=True)
description = models.CharField(max_length=255, null=True, blank=True)

def __str__(self):
return str(self.product_type)

def get_sub_type(self):
return str(self.product_sub_type)

class Meta:
db_table = 'ProductTypes'
unique_together = ('product_type', 'product_sub_type')


class Product(models.Model):
"""Products model."""

product_id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
product_type = models.ForeignKey(
ProductType,
related_name='related_products',
on_delete=models.SET_NULL,
blank=True, null=True
)
name = models.CharField(max_length=255, db_index=True)
code_name = models.CharField(max_length=255, null=True, blank=True)
href = models.CharField(max_length=500, blank=True, null=True)
full_name = models.CharField(max_length=255, null=True, blank=True, db_index=True)
manufacturer = models.ForeignKey(
Manufacturer,
related_name='manufactured_products',
on_delete=models.SET_NULL,
null=True, blank=True
)
packing = models.CharField(max_length=255, null=True, blank=True)
packing_detail = models.CharField(max_length=255, null=True, blank=True)
mrp = models.DecimalField(
max_digits=8,
decimal_places=2,
null=True, blank=True
)
created_at = models.DateTimeField(
'created at',
db_index=True,
default=timezone.now
)

def __str__(self):
return str(self.full_name)

class Meta:
db_table = 'Products'
unique_together = ('code_name', 'product_type')


serializers.py



class ProductTypeSerializer(serializers.ModelSerializer):
# Serialize/Deserialize ProductType instance.

class Meta:
model = ProductType
fields = (
'id', 'hsn',
'product_type', 'product_sub_type',
'description'
)
read_only_fields = ('id', )


class ProductSerializer(serializers.ModelSerializer):
# Serialize/Deserialize Product instance.

manufacturer = serializers.StringRelatedField()
manufacturer_id = serializers.PrimaryKeyRelatedField(read_only=True)
product_sub_type = serializers.SlugRelatedField(slug_field=????)

class Meta:
model = Product
fields = (
'product_id',
'product_type', 'product_sub_type',
'name', 'code_name',
'manufacturer', 'manufacturer_id',
'full_name',
'packing', 'packing_detail',
'mrp'
)
read_only_fields = (
'product_id', 'created_at',
'product_type', 'manufacturer_id'
)


with slug_field=product_sub_type it returns
ImproperlyConfigured at /products/
Field name product_sub_type is not valid for model Product.



with slug_field=product_type.product_sub_type it returns
AttributeError at /products/
Got AttributeError when attempting to get a value for field product_sub_type on serializer ProductSerializer.The serializer field might be named incorrectly and not match any attribute or key on the Product instance.



I want the serializer to return something like this:



{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"product_id": "fffcf7ba-5c6d-4190-96d2-cc9125e18e71",
"product_type": "1b3dd955-b67e-4ca3-9561-6d1704ff7c91",
"product_sub_type": "Capsules",
"name": "Enshine Toothpaste",
"code_name": null,
"manufacturer": "Leeford Healthcare Ltd",
"manufacturer_id": 2524,
"full_name": "Enshine Toothpaste",
"packing": null,
"packing_detail": null,
"mrp": null
}
]
}









share|improve this question





























    1















    I have two models ProductTypeModel and ProductModel, product_type is the foreign key in the product. Then I wrote a ModelSerializer for a product to get all the entries of ProductModel and along with some additional info.
    Now I'm unable to get product_sub_type from the ProductTypeModel in ProductSerializer



    I have tried SlugRelatedField in serializers, tried to set slug_field=product_sub_type and slug_field=product_type__product_sub_type and slug_field=product_type.product_sub_type



    models.py



    class ProductType(models.Model):
    """Product type model."""

    id = models.UUIDField(
    primary_key=True,
    default=uuid.uuid4,
    editable=False
    )
    hsn = models.ForeignKey(
    HSN,
    related_name='product_types',
    on_delete=models.SET_NULL,
    null=True, blank=True
    )
    product_type = models.CharField(max_length=255, null=True, blank=True)
    product_sub_type = models.CharField(max_length=255, db_index=True)
    description = models.CharField(max_length=255, null=True, blank=True)

    def __str__(self):
    return str(self.product_type)

    def get_sub_type(self):
    return str(self.product_sub_type)

    class Meta:
    db_table = 'ProductTypes'
    unique_together = ('product_type', 'product_sub_type')


    class Product(models.Model):
    """Products model."""

    product_id = models.UUIDField(
    primary_key=True,
    default=uuid.uuid4,
    editable=False
    )
    product_type = models.ForeignKey(
    ProductType,
    related_name='related_products',
    on_delete=models.SET_NULL,
    blank=True, null=True
    )
    name = models.CharField(max_length=255, db_index=True)
    code_name = models.CharField(max_length=255, null=True, blank=True)
    href = models.CharField(max_length=500, blank=True, null=True)
    full_name = models.CharField(max_length=255, null=True, blank=True, db_index=True)
    manufacturer = models.ForeignKey(
    Manufacturer,
    related_name='manufactured_products',
    on_delete=models.SET_NULL,
    null=True, blank=True
    )
    packing = models.CharField(max_length=255, null=True, blank=True)
    packing_detail = models.CharField(max_length=255, null=True, blank=True)
    mrp = models.DecimalField(
    max_digits=8,
    decimal_places=2,
    null=True, blank=True
    )
    created_at = models.DateTimeField(
    'created at',
    db_index=True,
    default=timezone.now
    )

    def __str__(self):
    return str(self.full_name)

    class Meta:
    db_table = 'Products'
    unique_together = ('code_name', 'product_type')


    serializers.py



    class ProductTypeSerializer(serializers.ModelSerializer):
    # Serialize/Deserialize ProductType instance.

    class Meta:
    model = ProductType
    fields = (
    'id', 'hsn',
    'product_type', 'product_sub_type',
    'description'
    )
    read_only_fields = ('id', )


    class ProductSerializer(serializers.ModelSerializer):
    # Serialize/Deserialize Product instance.

    manufacturer = serializers.StringRelatedField()
    manufacturer_id = serializers.PrimaryKeyRelatedField(read_only=True)
    product_sub_type = serializers.SlugRelatedField(slug_field=????)

    class Meta:
    model = Product
    fields = (
    'product_id',
    'product_type', 'product_sub_type',
    'name', 'code_name',
    'manufacturer', 'manufacturer_id',
    'full_name',
    'packing', 'packing_detail',
    'mrp'
    )
    read_only_fields = (
    'product_id', 'created_at',
    'product_type', 'manufacturer_id'
    )


    with slug_field=product_sub_type it returns
    ImproperlyConfigured at /products/
    Field name product_sub_type is not valid for model Product.



    with slug_field=product_type.product_sub_type it returns
    AttributeError at /products/
    Got AttributeError when attempting to get a value for field product_sub_type on serializer ProductSerializer.The serializer field might be named incorrectly and not match any attribute or key on the Product instance.



    I want the serializer to return something like this:



    {
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
    {
    "product_id": "fffcf7ba-5c6d-4190-96d2-cc9125e18e71",
    "product_type": "1b3dd955-b67e-4ca3-9561-6d1704ff7c91",
    "product_sub_type": "Capsules",
    "name": "Enshine Toothpaste",
    "code_name": null,
    "manufacturer": "Leeford Healthcare Ltd",
    "manufacturer_id": 2524,
    "full_name": "Enshine Toothpaste",
    "packing": null,
    "packing_detail": null,
    "mrp": null
    }
    ]
    }









    share|improve this question



























      1












      1








      1








      I have two models ProductTypeModel and ProductModel, product_type is the foreign key in the product. Then I wrote a ModelSerializer for a product to get all the entries of ProductModel and along with some additional info.
      Now I'm unable to get product_sub_type from the ProductTypeModel in ProductSerializer



      I have tried SlugRelatedField in serializers, tried to set slug_field=product_sub_type and slug_field=product_type__product_sub_type and slug_field=product_type.product_sub_type



      models.py



      class ProductType(models.Model):
      """Product type model."""

      id = models.UUIDField(
      primary_key=True,
      default=uuid.uuid4,
      editable=False
      )
      hsn = models.ForeignKey(
      HSN,
      related_name='product_types',
      on_delete=models.SET_NULL,
      null=True, blank=True
      )
      product_type = models.CharField(max_length=255, null=True, blank=True)
      product_sub_type = models.CharField(max_length=255, db_index=True)
      description = models.CharField(max_length=255, null=True, blank=True)

      def __str__(self):
      return str(self.product_type)

      def get_sub_type(self):
      return str(self.product_sub_type)

      class Meta:
      db_table = 'ProductTypes'
      unique_together = ('product_type', 'product_sub_type')


      class Product(models.Model):
      """Products model."""

      product_id = models.UUIDField(
      primary_key=True,
      default=uuid.uuid4,
      editable=False
      )
      product_type = models.ForeignKey(
      ProductType,
      related_name='related_products',
      on_delete=models.SET_NULL,
      blank=True, null=True
      )
      name = models.CharField(max_length=255, db_index=True)
      code_name = models.CharField(max_length=255, null=True, blank=True)
      href = models.CharField(max_length=500, blank=True, null=True)
      full_name = models.CharField(max_length=255, null=True, blank=True, db_index=True)
      manufacturer = models.ForeignKey(
      Manufacturer,
      related_name='manufactured_products',
      on_delete=models.SET_NULL,
      null=True, blank=True
      )
      packing = models.CharField(max_length=255, null=True, blank=True)
      packing_detail = models.CharField(max_length=255, null=True, blank=True)
      mrp = models.DecimalField(
      max_digits=8,
      decimal_places=2,
      null=True, blank=True
      )
      created_at = models.DateTimeField(
      'created at',
      db_index=True,
      default=timezone.now
      )

      def __str__(self):
      return str(self.full_name)

      class Meta:
      db_table = 'Products'
      unique_together = ('code_name', 'product_type')


      serializers.py



      class ProductTypeSerializer(serializers.ModelSerializer):
      # Serialize/Deserialize ProductType instance.

      class Meta:
      model = ProductType
      fields = (
      'id', 'hsn',
      'product_type', 'product_sub_type',
      'description'
      )
      read_only_fields = ('id', )


      class ProductSerializer(serializers.ModelSerializer):
      # Serialize/Deserialize Product instance.

      manufacturer = serializers.StringRelatedField()
      manufacturer_id = serializers.PrimaryKeyRelatedField(read_only=True)
      product_sub_type = serializers.SlugRelatedField(slug_field=????)

      class Meta:
      model = Product
      fields = (
      'product_id',
      'product_type', 'product_sub_type',
      'name', 'code_name',
      'manufacturer', 'manufacturer_id',
      'full_name',
      'packing', 'packing_detail',
      'mrp'
      )
      read_only_fields = (
      'product_id', 'created_at',
      'product_type', 'manufacturer_id'
      )


      with slug_field=product_sub_type it returns
      ImproperlyConfigured at /products/
      Field name product_sub_type is not valid for model Product.



      with slug_field=product_type.product_sub_type it returns
      AttributeError at /products/
      Got AttributeError when attempting to get a value for field product_sub_type on serializer ProductSerializer.The serializer field might be named incorrectly and not match any attribute or key on the Product instance.



      I want the serializer to return something like this:



      {
      "count": 1,
      "next": null,
      "previous": null,
      "results": [
      {
      "product_id": "fffcf7ba-5c6d-4190-96d2-cc9125e18e71",
      "product_type": "1b3dd955-b67e-4ca3-9561-6d1704ff7c91",
      "product_sub_type": "Capsules",
      "name": "Enshine Toothpaste",
      "code_name": null,
      "manufacturer": "Leeford Healthcare Ltd",
      "manufacturer_id": 2524,
      "full_name": "Enshine Toothpaste",
      "packing": null,
      "packing_detail": null,
      "mrp": null
      }
      ]
      }









      share|improve this question
















      I have two models ProductTypeModel and ProductModel, product_type is the foreign key in the product. Then I wrote a ModelSerializer for a product to get all the entries of ProductModel and along with some additional info.
      Now I'm unable to get product_sub_type from the ProductTypeModel in ProductSerializer



      I have tried SlugRelatedField in serializers, tried to set slug_field=product_sub_type and slug_field=product_type__product_sub_type and slug_field=product_type.product_sub_type



      models.py



      class ProductType(models.Model):
      """Product type model."""

      id = models.UUIDField(
      primary_key=True,
      default=uuid.uuid4,
      editable=False
      )
      hsn = models.ForeignKey(
      HSN,
      related_name='product_types',
      on_delete=models.SET_NULL,
      null=True, blank=True
      )
      product_type = models.CharField(max_length=255, null=True, blank=True)
      product_sub_type = models.CharField(max_length=255, db_index=True)
      description = models.CharField(max_length=255, null=True, blank=True)

      def __str__(self):
      return str(self.product_type)

      def get_sub_type(self):
      return str(self.product_sub_type)

      class Meta:
      db_table = 'ProductTypes'
      unique_together = ('product_type', 'product_sub_type')


      class Product(models.Model):
      """Products model."""

      product_id = models.UUIDField(
      primary_key=True,
      default=uuid.uuid4,
      editable=False
      )
      product_type = models.ForeignKey(
      ProductType,
      related_name='related_products',
      on_delete=models.SET_NULL,
      blank=True, null=True
      )
      name = models.CharField(max_length=255, db_index=True)
      code_name = models.CharField(max_length=255, null=True, blank=True)
      href = models.CharField(max_length=500, blank=True, null=True)
      full_name = models.CharField(max_length=255, null=True, blank=True, db_index=True)
      manufacturer = models.ForeignKey(
      Manufacturer,
      related_name='manufactured_products',
      on_delete=models.SET_NULL,
      null=True, blank=True
      )
      packing = models.CharField(max_length=255, null=True, blank=True)
      packing_detail = models.CharField(max_length=255, null=True, blank=True)
      mrp = models.DecimalField(
      max_digits=8,
      decimal_places=2,
      null=True, blank=True
      )
      created_at = models.DateTimeField(
      'created at',
      db_index=True,
      default=timezone.now
      )

      def __str__(self):
      return str(self.full_name)

      class Meta:
      db_table = 'Products'
      unique_together = ('code_name', 'product_type')


      serializers.py



      class ProductTypeSerializer(serializers.ModelSerializer):
      # Serialize/Deserialize ProductType instance.

      class Meta:
      model = ProductType
      fields = (
      'id', 'hsn',
      'product_type', 'product_sub_type',
      'description'
      )
      read_only_fields = ('id', )


      class ProductSerializer(serializers.ModelSerializer):
      # Serialize/Deserialize Product instance.

      manufacturer = serializers.StringRelatedField()
      manufacturer_id = serializers.PrimaryKeyRelatedField(read_only=True)
      product_sub_type = serializers.SlugRelatedField(slug_field=????)

      class Meta:
      model = Product
      fields = (
      'product_id',
      'product_type', 'product_sub_type',
      'name', 'code_name',
      'manufacturer', 'manufacturer_id',
      'full_name',
      'packing', 'packing_detail',
      'mrp'
      )
      read_only_fields = (
      'product_id', 'created_at',
      'product_type', 'manufacturer_id'
      )


      with slug_field=product_sub_type it returns
      ImproperlyConfigured at /products/
      Field name product_sub_type is not valid for model Product.



      with slug_field=product_type.product_sub_type it returns
      AttributeError at /products/
      Got AttributeError when attempting to get a value for field product_sub_type on serializer ProductSerializer.The serializer field might be named incorrectly and not match any attribute or key on the Product instance.



      I want the serializer to return something like this:



      {
      "count": 1,
      "next": null,
      "previous": null,
      "results": [
      {
      "product_id": "fffcf7ba-5c6d-4190-96d2-cc9125e18e71",
      "product_type": "1b3dd955-b67e-4ca3-9561-6d1704ff7c91",
      "product_sub_type": "Capsules",
      "name": "Enshine Toothpaste",
      "code_name": null,
      "manufacturer": "Leeford Healthcare Ltd",
      "manufacturer_id": 2524,
      "full_name": "Enshine Toothpaste",
      "packing": null,
      "packing_detail": null,
      "mrp": null
      }
      ]
      }






      python django serialization django-rest-framework






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 1 at 17:26









      Lucas Weyne

      383212




      383212










      asked Dec 31 '18 at 12:04









      Vineet SharmaVineet Sharma

      84




      84
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Providing the attributes slug_field and source works for a read-only SlugRelatedField. To allow writing in this field the queryset attribute must also be provided



          class ProductSerializer(serializers.ModelSerializer):
          ...
          product_sub_type = serializers.SlugRelatedField(
          slug_field='product_sub_type',
          source='product_type',
          queryset=ProductType.objects.all()
          )


          According to documentation slug_field should be a field that uniquely identifies any given instance






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53987296%2fhow-to-get-reverse-relation-in-django-serializers-slugrelatedfield%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Providing the attributes slug_field and source works for a read-only SlugRelatedField. To allow writing in this field the queryset attribute must also be provided



            class ProductSerializer(serializers.ModelSerializer):
            ...
            product_sub_type = serializers.SlugRelatedField(
            slug_field='product_sub_type',
            source='product_type',
            queryset=ProductType.objects.all()
            )


            According to documentation slug_field should be a field that uniquely identifies any given instance






            share|improve this answer






























              0














              Providing the attributes slug_field and source works for a read-only SlugRelatedField. To allow writing in this field the queryset attribute must also be provided



              class ProductSerializer(serializers.ModelSerializer):
              ...
              product_sub_type = serializers.SlugRelatedField(
              slug_field='product_sub_type',
              source='product_type',
              queryset=ProductType.objects.all()
              )


              According to documentation slug_field should be a field that uniquely identifies any given instance






              share|improve this answer




























                0












                0








                0







                Providing the attributes slug_field and source works for a read-only SlugRelatedField. To allow writing in this field the queryset attribute must also be provided



                class ProductSerializer(serializers.ModelSerializer):
                ...
                product_sub_type = serializers.SlugRelatedField(
                slug_field='product_sub_type',
                source='product_type',
                queryset=ProductType.objects.all()
                )


                According to documentation slug_field should be a field that uniquely identifies any given instance






                share|improve this answer















                Providing the attributes slug_field and source works for a read-only SlugRelatedField. To allow writing in this field the queryset attribute must also be provided



                class ProductSerializer(serializers.ModelSerializer):
                ...
                product_sub_type = serializers.SlugRelatedField(
                slug_field='product_sub_type',
                source='product_type',
                queryset=ProductType.objects.all()
                )


                According to documentation slug_field should be a field that uniquely identifies any given instance







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 31 '18 at 14:56

























                answered Dec 31 '18 at 12:53









                Lucas WeyneLucas Weyne

                383212




                383212
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53987296%2fhow-to-get-reverse-relation-in-django-serializers-slugrelatedfield%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                    Npm cannot find a required file even through it is in the searched directory