我在Django中有两个模型,我想在创建或更新History
的对象时自动创建Food
的对象,并设置food_price
History
属性}创建的price
对象的Food
属性。我的目的是有食物变化价格的历史。我怎样才能做到这一点?
我的models.py
是:
class Food(models.Model):
food_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=30, null=False, blank=False)
desc = models.TextField(max_length=200)
price = models.IntegerField(null=False, blank=False)
f_thumbnail = models.ImageField(upload_to=get_food_t_image_name)
DDD_data = models.ImageField(upload_to=get_food_d_image_name)
availability = models.BooleanField(default=True)
discount = models.IntegerField(default=0)
def __str__(self):
return '%s %s %s' % (self.name, self.category_id, self.price)
class History(models.Model):
id = models.AutoField(primary_key=True)
food_id = models.IntegerField()
food_price = models.IntegerField()
history_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s %s %s' % (self.id, self.food_id.name, self.food_id.price)
提前致谢。
答案 0 :(得分:2)
我认为你有两种方式。
__save__()
方法。在django模型中,(models.Model
),有__save__
方法。保存模型对象时,您可以执行继承此方法的其他功能。
有关详细信息,请查看official docs save()
signals
Django支持许多信号,包括django.db.models.signals
。它包括pre_save
,post_save
等。所以在保存模型对象之前(之后),你可以在signals
中做某事。
我认为__save__()
方法更适合您的目的。所以你的代码将是......
class Food(models.Model):
food_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=30, null=False, blank=False)
desc = models.TextField(max_length=200)
price = models.IntegerField(null=False, blank=False)
f_thumbnail = models.ImageField(upload_to=get_food_t_image_name)
DDD_data = models.ImageField(upload_to=get_food_d_image_name)
availability = models.BooleanField(default=True)
discount = models.IntegerField(default=0)
def __str__(self):
return '%s %s %s' % (self.name, self.category_id, self.price)
def save(self, force_insert=False, force_update=False, *args, **kwargs):
# you can add this for only existing model object
if self.pk:
# You can check if only 'price' field changed
_original_food = Food.objects.get(id=self.pk)
if _original_food.price != self.price:
# do somthing here like saving history...
History.objects.create(food_id=self.id, food_price=self.price)
super(Food, self).save(force_insert, force_update, *args, **kwargs)
super(Food, self).save(force_insert, force_update, *args, **kwargs)
这只是一个例子。你可以添加&修改你的代码。我希望它对你有所帮助。