简体   繁体   中英

Django restframework: How serialize two models queryset?

I have the following situation: A user can have more than one profile. Here is my models class. Something like this example:

models.py :

class Profile:
    name=models.Charfield()

class UserProfile:
   user=models.ForeignKey(User)
   profile = models.ForeignKey(Profile)

serializers.py :

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

Here I'm returning all my users by JSON but I would like to add a new field called profiles that returns all ids profiles that the user have.

{ "id": 1,
  "name" : "John"
  ....
  profiles = [1, 2]
} 

How can I get(query) all profiles that the user have and add them on my final JSON?

on the UserSerializer declare the field profile as PrimaryKeyRelatedField

profiles = serializers.PrimaryKeyRelatedField()

By default this field is read-write, although you can change this behavior using the read_only flag.

see docs

1) Simplify relations - only User and Profile models needed in this case, you don't have to store explicit relation in UserProfile table as the same could be done in Profile model, as long as you don't need Users to share profiles with other Users.

2) Create ProfileSerializer

3) Add profiles field to UserSerializer with many=True property & provide reference in 'source' property Please reffer to these docs as they are really good http://www.django-rest-framework.org/api-guide/serializers/

Another thing to mention, creating UserProfile is depricated and in new versions of Django you can extend basic User model using setting property AUTH_USER_MODEL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM