How do I show specific field in foreign key model, in Django+React app?

Viewed 222

so I have a Django+React app, and having trouble with something. Obviously, I've created REST API with Django and fetching it with React. Let me show you the code first.
models.py (Django)

class Category(models.Model):
    category_name = models.CharField(max_length = 20)

class Content(models.Model):
    category = models.ManyToManyField(Category)
    key_line = models.CharField(max_length = 100, null=True)
    body = models.TextField(blank=True, null=True)

views.py (Django)

@api_view(['GET'])
def book_list(request):
    books = Content.objects.all()
    serialized = ContentsSerializer(books, many=True)
    
    return Response(serialized.data)

React component

class Books extends Component {
    constructor(props){
        super(props);
        this.state = {
        }
    }

    componentDidMount() {
        this._getBookList();
    }

    _renderBookList = () => {
        const books = this.state.bookList_object.map((this_book, index) => {
        return <BakeList 
        key_line={this_book.key_line}
        body={this_book.body}
        category={this_book.category_name}
        />
        }) 
        return books
    }
   
    _getBookList = async () => {
        const book = await this._callApiBookList();
        this.setState({
        bookList_object : book
        })
    }
    
    _callApiBookList = () => {
        return fetch("https://api.book.shop/api/books/")
        .then((response) => response.json())
        .catch((err) => console.log(err))
    }

    render() {
        return(
            <div>this._renderBookList()</div>
    )
}

BookList.js

class CakeList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            page : 'home'
        }
    }
    render() {
        
        return (
                <div>{this.props.key_line}</div>
                <div>{this.props.body}</div>
                <div>{this.props.category}</div>
        )
    }

Now the problem is in the {this.props.category} line in BookList.js component.
What I want to get in the screen is category_name, but what I get is id. How do I change the field that is displayed on the screen?

Thank you very much in advance :)

1 Answers

In React Component Category ={this_book.category.category_name} Because it's manytomany field with Category class So you should call for category_name too

Related