How to get a list of all objects from two models associated with one field

I have a client profile model as follows

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    address = models.CharField(max_length=200)

      

and auth user model. I want a list of all custom objects with their json address:

{
    //auth_user fields
    "username": "username",
    "first_name": "first_name",
    "last_name": "last_name", 
    "is_active": true, 
    "is_superuser": false, 
    ....
    ....
    //UserProfile fields
    address: "address"
}

      

By doing serializers.serialize(User.objects.all())

, I was only able to get the user's user data. How to get associated profile data also with user data?

+3


source to share


2 answers


The easy way is to serialize each model separately. Also, if you really need to return the json of a single entry for both models, you can create a list of dictionaries from the models manually (for example by iterating) and then use the json.dumps

Django serializer instead:

import json
# ...

r = []
for user in User.objects.all():
    r.append({
        'username': user.username,
        # ....
        'address': user.userprofile.address
    })

 my_json = json.dumps(r)

      



Haven't tested this, but I hope you get the idea.

0


source


To get serialized nested objects you can use the django-rest-framework part - http://www.django-rest-framework.org/api-guide/relations/



class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track

class UserSerializer(serializers.ModelSerializer)
    userprofile = UserProfileSerializer(many=False)

    class Meta:
        model = User

serializer = UserSerializer(user)
print(serializer.data)

      

0


source