简体   繁体   English

创建后Django设置模型字段

[英]Django set model fields after create

I have a model Movie and a Model DefaultMoviePriceFor which saves the default prices for a specific genre: 我有一个Movie模型和一个DefaultMoviePriceFor模型,用于保存特定类型的默认价格:

class Movie(models.Model):
    name = models.TextField('name', null=True)
    genre = models.TextField('genre', null=True)
    price = models.IntegerField('price', default=0)

class DefaultMoviePriceForGenre(models.Model):
    genre = models.TextField('genre', null=True)
    price = models.IntegerField('price', default=0)

Now I would like to fill up Movie.price with the default price of the Movie.genre everytime an object of Movie is instantiated. 现在,我想在每次实例化Movie对象时用Movie.genre的默认价格填充Movie.price。

Is there any good way to do so? 有什么好办法吗? I have SQL triggers in my head, they could do that, don't they? 我脑子里有SQL触发器,他们可以做到,不是吗? How is it done in django? 如何在Django中完成?

One way to do this is with the pre-save signal . 一种方法是使用预保存信号 This will be fired immediately before any instance of the model is saved, and will received a created boolean arg that will let you set the price only if the object is new. 这将在保存任何模型实例之前立即被触发,并且将收到一个created布尔型arg,仅当对象是新的时,该布尔型arg允许您设置价格。

There's also a post-save signal if for some reason you want to do it after saving, EG because your behavior depends on the new instance's PK. 如果出于某种原因要在保存后执行此操作(例如EG),则还会有一个保存后的信号,因为您的行为取决于新实例的PK。 But pre-save should work here. 但是预保存应该在这里起作用。

Alternatively, you can override the model class's save method. 或者,您可以覆盖模型类的save方法。 https://docs.djangoproject.com/en/2.1/topics/db/models/#overriding-model-methods https://docs.djangoproject.com/en/2.1/topics/db/models/#overriding-model-methods

See this answer for some discussion of the pros and cons of the two approaches: Django signals vs. overriding save method 有关两种方法的优缺点的讨论,请参见此答案: Django信号vs.覆盖保存方法

This is all assuming the desired behavior is exactly as described - look up the current default price of the genre when the instance is created and preserve it independently of future changes to the genre. 所有这些都假设所需的行为与所描述的完全相同-创建实例时查找该类型的当前默认价格,并与将来对该类型的更改无关地保存该默认价格。 If you want to do something more flexible - EG say "horror movies cost X now unless overridden, but if I change the default genre price later they should all update" you might be best served with a method on the Movie class that computes the price based on current state rather than setting it at creation and breaking that connection. 如果您想做些更灵活的事情-例如,说“恐怖电影除非被覆盖,否则现在的成本是X,但是如果以后更改默认类型的价格,它们都应该全部更新”,那么最好在Movie类上使用一种方法来计算价格基于当前状态,而不是在创建和断开连接时进行设置。 But it depends what you want. 但这取决于您想要什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM