Skip to content
Advertisement

Getting ID instead of Name in list

I am doing CRUD project with foreign keys and I am using serializers.I want to get the Name of the categories,sub categories,color and size instead of thier IDs serializer:

JavaScript

models are:

JavaScript
JavaScript

below is the insert function

JavaScript

show function

JavaScript

instead of name of categories subcategories color size etc I am getting id below is how the product_insert looks on webpage enter image description here

where is the problem here?

Advertisement

Answer

You need to specify in the serializer that you want the foreign keys to be displayed as strings:

JavaScript

This displays whatever is returned by the __str__ method of the object, which you can override to return its name.

JavaScript

Alternative

If you do not want to touch your serializer (StringRelatedField is read-only, which may mean there are certain operations you cannot do, like POST), you can always add extra parameters to your serialized data by doing something like this:

JavaScript

Then, you can simply use the category_display_name, color_display_name, size_display_name and sub_category_display_name to render your table in the template (of course, you need to define the __str__ methods of the Categories, Colors, Size and SUBCategories models here too). This may lead to performance issues when working with large databases, though, so not really recommended…

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement