简体   繁体   中英

How do I reference other FIELD using foreign key in Django?

So I'm using Django and have a foreignkey field. Let me show you the model first.

class Book(models.Model):
    objects = models.Manager()
    title = models.CharField(max_length = 30)
    author = models.CharField(max_length = 20)

class Content(models.Model):
    objects = models.Manager()

    source = models.ForeignKey("Book", related_name='book', on_delete=models.CASCADE)
    key_line = models.CharField(max_length = 100, null=True)

I used serializer to load the api to my React front end. But then, the source field is displayed as integer, which probably is the id of Book model.

However what I want to do is load the title of each book in the source field.
Any advice?

FYI, other codes.
views.py

@api_view(['GET'])
def each_book(request, pk):
    this_book = Content.objects.get(pk=pk)
    serialized = ContentSerializer(this_book, context={'request':request})
    return Response(serialized.data)

serializers.py

class ContentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Content
        fields = '__all__'

You could just pass book to the context field and call it like:

@api_view(['GET'])
def each_book(request, pk):
    this_book = Content.objects.get(pk=pk)
    serialized = ContentSerializer(this_book, context={'request':request, 'book': this_book})
    return Response(serialized.data)

Then

class ContentSerializer(serializers.ModelSerializer):
        book_title = serializers.SerializerMethodField()
        class Meta:
            model = Content
            fields = '__all__'
        
        def get_book_title(self, obj): # Note that obj is `content` in this case.
             return self.context['book'].title

Make sure you include it in your fields too. Not sure if it works with __all__ . If it doesn't, then just explicitly write all your fields out with the book_title field included.

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