Home > Back-end >  Python - Django: select mulitple fields from different models to serialize into one json result
Python - Django: select mulitple fields from different models to serialize into one json result

Time:12-12

I'm currently working in my first Django project and am using the authentication mechanism that is included with Django. I currently have a game model with a foreign key relationship to a user in the auth_user table. Here are the following fields:

class Game(models.Model):
    game_id = models.UUIDField(default=uuid.uuid4, editable=False, max_length=10)
    host = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE)
    join_code = models.CharField(max_length=100, null=True)
    active = models.BooleanField(default=True)

I currently have a view method that just grabs all of the active game objects, and then passes those results into a serializer that serializes the data to be returned to the client.

def get(self, request, format=None):
    games = Game.objects.filter(active__exact=True)
    serializer = GameSerializer(games, many=True)
    return Response(serializer.data)

I want to add the username and email fields that are in AUTH_USER_MODEL to the results to be serialized, but I haven't been able to find examples of adding specific fields from a related model to the results that are serialized. Basically, I'm trying to figure out the django model equivalent of the following SQL statement

select u.username, u.email, g.* from game g
inner join AUTH_USER_MODEL u on u.user_id = g.host_id

Finally, once I have the results from that sort of query, how would I serialize the combined objects? Do I need to create another model that's a combination of the two models?

CodePudding user response:

I found what I was looking for, I can use a nested serializer, here's the stack overflow answer that pointed me in the right direction: Serialize data from multiple models django

Here is the Django rest framework documentation: https://www.django-rest-framework.org/api-guide/relations/#nested-relationships

CodePudding user response:

Your serializer should look like this -

class AuthUserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = AuthUserModel
        fields = ('username', 'email')

class GameSerializer(serializers.ModelSerializer):
    auth = AuthUserModelSerializer()

    class Meta:
        model = Game
        fields = '__all__'

Use your serializer where you want -

serializer = GameSerializer()
  • Related