我有以下问题:我想将模型pre_save函数中的数据传递给我的views.py
原因是在我的pre_save函数中,生成了一个唯一的order_id。此唯一订单ID还必须保存在会话ID中(request.session ['order_id'] = unique_order_id)。模型不接受请求,所以我试图将它保存在我的views.py中,但是如何在那里获得生成的唯一订单ID?
感谢您的帮助!
views.py
def another_view(request):
if request.POST:
# Generate unique order_id
x = Order().save()
request.session['order_id'] = x
# This is how I hoped it to solve, but x is not passing any data, even when adding a return variable in pre_save
models.py
# Imports (removed)
# Create your models here.
class Order(models.Model):
order_id = models.CharField(max_length=10, unique=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.order_id)
def order_pre_save_receiver(sender, instance, *args, **kwargs):
instance.order_id = unique_id_generator(instance)
# Here the unique order id is generated. Additionally I want to save this id as a session.
pre_save.connect(order_pre_save_receiver, sender=Order)
答案 0 :(得分:1)
当你致电x = Order().save()
时,你正在创建一个订单对象来更新它而不是保留它
save()
方法不返回任何模型对象,而是使用
所以你需要做的是
x = Order()
x.save() # at this point pre_save is called and unique id is updated
x.order_id # will be your updated order id