在Django中创建其他对象后如何自动创建新对象? [英] How create new object automatically after creating other object in django?
本文介绍了在Django中创建其他对象后如何自动创建新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有两个课程。
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,....)
在数据库中每次添加新Book对象后,应自动创建
新订单对象。并自动将order_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.
我该怎么做?
感谢
推荐答案
您可以覆盖Book的保存方法:
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()
如果应该用插入时间填充auto_now_add = True,也可以将它添加到order_datetime:
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)
这篇关于在Django中创建其他对象后如何自动创建新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文