简体   繁体   English

如何设置相互关联的Django模型字段

[英]How to set interrelated Django model Fields

I have the following simplified problem. 我有以下简化的问题。 Say that I have two Django models, namely a (P)roject and (H)ourly which stores hourly values for the project. 假设我有两个Django模型,分别是(P)roject和(H)ourly,它们存储项目的小时值。

Now lets assume that there is a simple relation between these entities, eg: Hy = 2*Hx + P.par. 现在假设这些实体之间存在简单关系,例如:Hy = 2 * Hx + P.par。 Is there an elegant way to implement this? 是否有一种优雅的方法来实现这一目标? Where to put the help function: 放置帮助功能的位置:

def calc_y(x, par):
    return 2*x+par

class P(models.Model):
    par = FloatField()

class H(models.Model):
    p = models.ForeignKey(P, on_delete.CASCADE)
    x = FloatField()
    y = FloatField()

In case you do not need to query on y (only obtain the value), we can make it a property instead: 如果您不需要查询y (仅获取值),我们可以将其设置为属性:

class P(models.Model):
    par = FloatField()

class H(models.Model):
    p = models.ForeignKey(P, on_delete.CASCADE)
    x = FloatField()

    @property def y(self): return calc_y(self.x, self.p.par)

So we do not store it in the database: the property is evaluated when needed. 因此,我们不将其存储数据库中:在需要时评估属性。 So if you have a H instance h , then hy will let Python evaluate the value and return it. 因此,如果您有一个H实例h ,那么hy将让Python评估该值并返回它。

The advantage of doing so is that we avoid data duplication, so it can not happen that the relation between the three variables is not satisfied, we also save on memory, since the database table will be smaller. 这样做的好处是避免了数据重复,因此不会发生三个变量之间的关系不满足的情况,而且由于数据库表较小,因此我们还节省了内存。

A problem with this approach is that since the value is not stored explicitly, querying on y is impossible (or at least not without some tricks). 这种方法的问题在于,由于未显式存储值,因此不可能查询y (或者至少没有一些技巧)。 So we can not easily query the database for all H s where y < 0.5 for example. 因此,我们无法轻松地在数据库中查询所有H ,例如y < 0.5

You should put all the code with business logic in services.py of your Django app. 您应该将所有带有业务逻辑的代码放入Django应用的services.py中。

For example, your case should go like, 例如,您的情况应该是这样,

from .models import H, P

def calculate_y(x, par):
    obj = H.objects.get(x=x)  # if x is unique else use id
    obj.y = 2 * x + par
    obj.save(update_fields['y'])

You can call this function right after creating an object for H. 您可以在为H创建对象后立即调用此函数。

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

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