python – Retrieving a Record on a ForeignKey Dependency


When I pick up a Sticker, all messages related to this Sticker are recorded in the message field, and you only need to pick up the last message

class Sticker(models.Model):
    board = models.ForeignKey(Board, related_name='stickers')
    flags = models.ForeignKey(Flag, related_name='stickers')

class Messages(models.Model):
    text = models.TextField()
    date = models.DateTimeField()
    sticker = models.ForeignKey(Sticker, related_name='messages')
    attachment = models.URLField(blank=True)

class MessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Messages
        fields = ('date', 'text', 'id', 'sticker')

class StickerSerializer(serializers.ModelSerializer):
    messages = MessageSerializer(Messages.objects.order_by('date')[0], many=True)

    class Meta:
        model = Sticker
        fields = ('id', 'board', 'flags', 'messages')

class Stickers(ListAPIView):
    permission_classes = ()
    # authentication_classes = (TokenAuthentication, )

    def get(self, request, board_id):
        stickers = Sticker.objects.get(board=board_id)
        serializer = StickerSerializer(stickers)
        return Response(


If you only want the last message then try this

class StickerSerializer(serializers.ModelSerializer):
    last_message = MessageSerializer(source='messages.last', many=False)

class Meta:
    model = Sticker
    fields = ('id', 'board', 'flags', 'last_message')
Scroll to Top