PythonNewbie
PythonNewbie

Reputation: 828

Append value to Django model

I have 2 DB Models:

class Book(models.Model):
    title = models.CharField(max_length=150, null=False)
    author = models.CharField(max_length=150, null=False)
    date_pub = models.DateField(verbose_name="Date Published")

and

class Customer(models.Model):
    name = models.CharField(max_length=25, null=False)
    surname = models.CharField(max_length=35, null=False)
    age = models.IntegerField(null=False)
    book = models.ForeignKey(to=Book, on_delete=models.CASCADE)

My app was created recently, so i use manage.py shell to insert data to these models.

For example, let's say I created books with title "Kolobok" and "Zolotaya Ribka". Next, I created customer "Vasya". When I created customer "Vasya", I pointed field book as "Kolobok". But over time, i want to append book "Zolotaya Ribka" to "Vasya" 's books.

How i can to that?

Upvotes: 2

Views: 5726

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476534

You likely need a ManyToManyField [Django-doc] instead. A many-to-many field means that a Customer can be linked to zero, one or more Books (so here that would mean the customer bought zero, one or more books), and a Book can be linked to zero, one or more customers (so a book is bought by zero, one or more customers).

We thus can remodel this by introducing a field books:

class Customer(models.Model):
    name = models.CharField(max_length=25, null=False)
    surname = models.CharField(max_length=35, null=False)
    age = models.IntegerField(null=False)
    books = models.ManyToManyField(Book)

Then we can construct for example the books and the customer like you did:

b1 = Book.objects.create(title='Kolobok', author='')
b2 = Book.objects.create(title='Zolotaya Ribka', author='')

next we can create a customer:

c1 = Customer.objects.create(name='Vasya', surname='', age=73)

and then we can link the two books b1 and b2 to c1:

c1.books.add(b1, b2)

See the documentation on many-to-many relationships for more information.

Upvotes: 6

Related Questions