How can I display the values from a ManyToMany Field in Django instead of their Id?

Viewed 1031

I have two models

  1. Influencer
class Influencer(models.Model):

    full_name = models.CharField('Full Name',max_length=255)
    username = models.CharField('Username',max_length=255,unique=True)
    photo = models.URLField(blank=True,max_length = 500)
    email_id = models.EmailField('Email Id',blank=True,max_length=500)
    categories = models.ManyToManyField(Category,blank=True,max_length=400)

and 2. Categories

class Category(models.Model):
    name = models.CharField(max_length=400)

    def __str__(self):
        return self.name

Influencer has a many to many field categories.

My views functions to display all the influencers is:

def index(request):
    influencers = Influencer.objects.all().order_by('followers')

    paginator = Paginator(influencers,16)
    page = request.GET.get('page')
    paged_listings = paginator.get_page(page)
    user_list = UserList.objects.all().filter(user_id = request.user.id)  
    queryset = list(chain(paged_listings,user_list))
    ser_query = serializers.serialize('json', queryset)
    return HttpResponse(ser_query,content_type='application/json')

The HttpResponse contains category id's instead of category names, something like this: enter image description here

where categories is an array which contains category id's. I want to display the name of categories instead of their id's.

I think this can be achived using Django Rest Framework nested serializer, but at this moment I am not using DRF.

2 Answers

there is an natural_key method in django to convert id to string

add natural_key method in your models.py file

class Category(models.Model):
    name = models.CharField(max_length=400,)

    def __str__(self):
        return self.name

    def natural_key(self):
        return self.name

and then in your serializers.serializer you need to pass use_natural_foreign_keys=True,

ser_query = serializers.serialize('json', influencers,indent=2,use_natural_foreign_keys=True,)

convert your array element --integer value -- into string then access from a dict or a tuple which contains categories with their ids

id_to_category=["0":"whatever your category is","1":"whatever your category is","2":"whatever your category is","3":"whatever your category is"]

id=str(ur_array[id])

category_name=id_to_category[id]
Related