1

For example, I have two classes.

class Book(models.Model):
    title = models.CharField (...)    
    author = models.CharField (...)
    price = models.Integer(...)

class Order(models.Model)
    order_datetime = models.DateTimeField()
    order_book = models.ForeignKey(Book,....)

New Order object should be created automatically after each addition of a new Book object in the database. And order_book fielt should be autocomplited with correspending book object.

How can I make it?

Thanx for the help!

1

1 Answer 1

3

You can override the save method of Book:

class Book(models.Model):
    title = models.CharField (...)    
    author = models.CharField (...)
    price = models.Integer(...)

    def save(self, *args, **kwargs):
        is_new = True if not self.id else False
        super(Book, self).save(*args, **kwargs)
        if is_new:
            order = Order(order_book=self)
            order.save()

You can also add auto_now_add=True to order_datetime if it's supposed to be filled with insertion time:

order_datetime = models.DateTimeField(auto_now_add=True)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanx a lot, nima! I will try to use it.
this line I can't understand ``` is_new = True if not self.id else False
You need to to decide whether the Book is saved for the first time, before calling super because it will have an id after that anyways.
when I try to do this I get an error in order_book, Im guessing its because when creating an order the book is not a parameter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.