Python 使用ForeignKey在Django中定义属性方法
我正在使用Django应用程序,其中我有两种型号:Python 使用ForeignKey在Django中定义属性方法,python,python-3.x,django,Python,Python 3.x,Django,我正在使用Django应用程序,其中我有两种型号:Store和Turn。存在一对多关系,其中商店有许多需要处理的轮次。代码如下: class Store(models.Model): name = models.CharField(max_length=20) adress = models.CharField(max_length=40) image = models.ImageField(upload_to=) @property def avera
Store
和Turn
。存在一对多关系,其中商店有许多需要处理的轮次。代码如下:
class Store(models.Model):
name = models.CharField(max_length=20)
adress = models.CharField(max_length=40)
image = models.ImageField(upload_to=)
@property
def average_wait_time(self):
return #here's the problem
def __str__(self):
return self.name
class Turn(models.Model):
store = models.ForeignKey(Store, on_delete=models.SET_NULL, null=True)
creation_time = models.TimeField(auto_now=True)
completion_time = models.TimeField(blank=True, null=True)
def complete(self):
self.completion_time = timezone.now()
def __str__(self):
return f'Turno a las {creation_time} para el Negocio {completion_time}'
如您所见,我需要使用一个@property
方法来计算存储中的平均等待时间,该时间由轮次持续时间的平均值确定。我怎样才能做到这一点?我无法从“存储”模型访问Turn
模型…相关\u名称
您需要的是ForeignKey
中的related\u name
参数。其工作原理如下:
store = models.ForeignKey(Store, on_delete=models.SET_NULL, null=True, related_name="turns")
store = Store.objects.get(id=1) # get a store
turns = store.turns
这意味着您现在可以访问特定商店的所有轮次,如下所示:
store = models.ForeignKey(Store, on_delete=models.SET_NULL, null=True, related_name="turns")
store = Store.objects.get(id=1) # get a store
turns = store.turns
上面的turns
将是Turn
对象的查询集
另外请注意,如果您没有指定相关的\u名称
django实际上会通过将\u set
以小写形式添加到相关模型名称的末尾来为您自动创建一个名称,您可以对以下内容执行相同的操作:
turns = store.turn_set
但最好明确地命名相关的\u名称
你的特殊情况
您也可以使用aggregate
和Avg
,但上面可能是可以的