Django How to Serialize from ManyToManyField and List All

2024/11/17 6:52:17

I'm developing a mobile application backend with Django 1.9.1 I implemented the follower model and now I want to list all of the followers of a user but I'm currently stuck to do that. I also use Django Rest Framework.

This is my UserProfile model

class UserProfile(models.Model):# Linking UserProfile to User model.user = models.OneToOneField(User)city = models.CharField(null=True, max_length=30, blank=True)gender = models.CharField(null=True, max_length=10, blank=True) # m for male, f for female# TODO: Fix the picture later.#  picture = models.ImageField(upload_to='profile_images', blank=True)age = models.IntegerField(null=True, blank=True)caption = models.CharField(null=True, max_length=40, blank=True)following_count = models.IntegerField(default=0)follower_count = models.IntegerField(default=0)post_count = models.IntegerField(default=0)like_count = models.IntegerField(default=0)date = models.DateTimeField(default=datetime.now(), blank=True)is_protected = models.BooleanField(default=False)is_facebook_created_user = models.BooleanField(default=False)facebook_id = models.CharField(default='', blank=True, max_length=350)picture_url = models.URLField(blank=True, max_length=100, null=True)followings = models.ManyToManyField('self', related_name='following', symmetrical=False)followers = models.ManyToManyField('self', related_name='follower', symmetrical=False)blocking = models.ManyToManyField('self', related_name='block', symmetrical=False)blocked_by = models.ManyToManyField('self', related_name='blocked', symmetrical=False)def block_user(self,username):other = UserProfile.objects.get(user__username=username)if not self.is_blocking(username):self.blocking.add(other)other.blocked_by.add(self)return Trueelse:return Falsedef unblock_user(self, username):other = UserProfile.objects.get(user__username=username)if self.is_blocking(username):self.blocking.remove(other)other.blocked_by.remove(self)return Trueelse:return Falsedef follow_user(self, username):other = UserProfile.objects.get(user__username=username)if not self.is_following(username):self.followings.add(other)self.following_count = self.followings.all().count()self.save()other.followers.add(self)other.follower_count = other.followers.all().count()other.save()return Trueelse:return Falsedef unfollow_user(self, username):other = UserProfile.objects.get(user__username=username)if self.is_following(username):self.followings.remove(other)self.following_count = self.followings.all().count()self.save()other.followers.remove(self)other.follower_count = other.followers.all().count()other.save()return Trueelse:return Falsedef is_blocking(self,username):return self.blockings.all().filter(user__username=username).exists()def is_blocked_by(self,username):return self.blocked_by.all().filter(user__username=username).exists()def is_following(self, username):  #returns Boolreturn self.followings.all().filter(user__username=username).exists()def is_followed_by(self, username):  #returns Boolreturn self.followers.all().filter(user__username=username).exists()def __unicode__(self):return self.user.usernamedef get_token(self):try:token = Token.objects.get(user_id=self.user_id)except:token = 'error'return tokendef get_username(self):return self.user.username

As you see, I user ManyToManyField for followers. Now I want to list followers of a user but I don't want to list just all of their information since it's unnecessary. I just want to list their usernames because no need for whole information and it's just a waste.

Here is my followers view.

@api_view(['GET'])
def get_followers(request):username = request.query_params.get('username', None)if username is not None:if        UserProfile.objects.all().filter(user__username=username).exists():wanted = UserProfile.objects.get(user__username=username)followers = wanted.followers.all()serializer = FollowerSerializer(followers)return JsonResponse(serializer.data)else:return JsonResponse({"result": "user_does_not_exist"})else:#TODO: return current user's followersreturn JsonResponse({"result": "provide_username"})

Also I added a serializer for only followers of user.

class FollowerSerializer(serializers.ModelSerializer):class Meta:model = UserProfilefield = ('followers',)

The problem is, it just lists the all of the user information and it doesn't give usernames but it only lists their id's which i can't do anything.

I forgot to mention that I did think of using ListAPIView but I can't get the username parameter with that. If there is a way of getting the parameter, I could also use ListAPIView for followers.

How can I fix this problem and list only their usernames? Any help will be appreciated.

Answer

I think what you need is the nested serializer:

class FollowerSerializer(serializers.ModelSerializer):username = serializers.CharField(source='user__username')class Meta:model = UserProfilefields = ('username', )class FollowerSerializer(serializers.ModelSerializer):followers = FollowerSerializer(many=True, read_only=True)class Meta:model = UserProfilefields = ('followers', )
https://en.xdnf.cn/q/71576.html

Related Q&A

PyDrive and Google Drive - automate verification process?

Im trying to use PyDrive to upload files to Google Drive using a local Python script which I want to automate so it can run every day via a cron job. Ive stored the client OAuth ID and secret for the G…

Using rm * (wildcard) in envoy: No such file or directory

Im using Python and Envoy. I need to delete all files in a directory. Apart from some files, the directory is empty. In a terminal this would be:rm /tmp/my_silly_directory/*Common sense dictates that i…

cant import django model into celery task

i have the following task:from __future__ import absolute_importfrom myproject.celery import appfrom myapp.models import Entity@app.task def add(entity_id):entity = Entity.objects.get(pk=entity_id)retu…

Running unit tests with Nose inside a Python environment such as Autodesk Maya?

Id like to start creating unit tests for my Maya scripts. These scripts must be run inside the Maya environment and rely on the maya.cmds module namespace.How can I run Nose tests from inside a runnin…

Python Newline \n not working in jupyter notebooks

Im trying to display the tuples of a postgreSQL table neatly in my Jupyter Notebook, but the newline \n escape character doesnt seem to work here (it works for my python scripts w/ same code outside of…

Dynamically calling functions - Python

I have a list of functions... e.g.def filter_bunnies(pets): ...def filter_turtles(pets): ...def filter_narwhals(pets): ...Is there a way to call these functions by using a string representing their nam…

py2exe windows service problem

I have successfully converted my python project to a service. When using the usual options of install and start/stop, everything works correctly. However, I wish to compile the project using py2exe, …

Draw a cumulative chart from a pandas dataframe?

I have a dataframe as follows:df = pd.DataFrame({cost_saving: [10, 10, 20, 40, 60, 60],id: [a, b, c, d, e, f]})How can I draw a cumulative chart of the savings?Im thinking of a line chart with number …

Sort a complex Python dictionary by just one of its values

I am writing a little optimization tool for purchasing stamps at the post office.In the process I am using a dictionary, which I am sorting according to what I learned in this other "famous" …

How to modularize a Python application

Ive got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have…