user2597209 user2597209 - 1 year ago 91
Python Question

List Field in Model-- Django

I am newbie in django,working on rest API framework. I want to ask the user for certain details to be put in html format, like popularity, name of some book.

A book can belong to various category such as Friction, Romantic, Action.
So I want to have a list Field for category.
Two options can be given, one ask the user to enter the category and append in the list at the backend. Or provide a list from which user can choose.

Have tried the below code in model.py

from django.db import models

class Category(models.Model):
category = models.CharField(max_length=100)

def __str__(self):
return self.category


class Books(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField()
category = models.ManyToManyField(Category)
#category = models.ForeignKeyField(Category) #tried Foreign key Model Field also


def __str__(self):
return self.name


Please help me out. Is that the correct approach or should try something else.

Thanks in advance.

Its working fine, But instead of showing the values on the admin panel, it shows Category Object in the Books Model Table.

[
{
"name": "Harry Potter",
"date": 03-03-2014,
"category": 6
}
]


Where at category 6 there is String value as "Magical"

am I missing anything

Answer Source

Each book belongs to only one category (or genre), so what you need is a foreign key (not many to many relationship). Your Book model should look like below:

class Book(models.Model):
    title = models.CharField(max_length=100)
    publication_date = models.DateTimeField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

Notes:

  • It's better to use publication_date or published instead of date to not shadow date in case you imported it from datetime module for example.
  • A book is characterized by its title (so it's better to call the first field title instead of name)
  • on_delete=models.CASCADE means if a category is deleted, all its related books will be deleted too.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download