gpt4 book ai didi

带有 self 实例的 Django 模型方法

转载 作者:行者123 更新时间:2023-12-01 17:32:53 25 4
gpt4 key购买 nike

我正在尝试将一些功能逻辑移至模型的方法中(而不是 View 中),我认为它属于该位置:

class Spans(models.Model):
snow = models.IntegerField()
wind = models.IntegerField()
exposure = models.CharField(max_length=1)
module_length = models.IntegerField()
max_roof_angle = models.IntegerField()
building_height = models.IntegerField()
importance_factor = models.IntegerField()
seismic = models.DecimalField(max_digits=4, decimal_places=2)
zone = models.IntegerField()
profile = models.CharField(max_length=55)
tilt_angle = models.IntegerField()
span = models.DecimalField(max_digits=18, decimal_places=15)

def get_spans(self, snow_load, wind_speed, module_length):
"""
Function to get spans.
"""
spans = self.objects.filter(
snow=snow_load,
wind=wind_speed,
exposure='B',
module_length__gte=module_length,
max_roof_angle=45,
building_height=30,
importance_factor=1,
seismic=1.2,
zone=1,
profile='worst'
).order_by('snow', 'module_length', 'span')
return spans

但是,我有点不确定如何调用它。在外壳中我尝试过:

>>> possible_spans = Spans.get_spans(0, 85, 54)

>>> possible_spans = Spans.get_spans(Spans, 0, 85, 54)

但我收到错误:

TypeError: unbound method get_spans() must be called with Spans instance as first argument (got int instance instead) 

TypeError: unbound method get_spans() must be called with Spans instance as first argument (got ModelBase instance instead)  

我知道我在这里遗漏了 python 逻辑中的一些基本内容,但我不确定它是什么。

任何帮助将不胜感激。

最佳答案

方法需要使用实例来调用,因为方法调用将其作为默认的 self 参数。例如,

instance = Spans.objects.get(id=1)
instance.get_spans(0, 85, 54)

或者如果您想使用类本身进行调用。您必须手动传递实例

instance = Spans.objects.get(id=1)
Spans.get_spans(instance, 0, 85, 54)

更新:您正在寻找的内容可以使用静态方法来实现

@staticmethod
def get_spans(snow_load, wind_speed, module_length):
"""
Function to get spans.
"""
spans = Spans.objects.filter(
snow=snow_load,
wind=wind_speed,
exposure='B',
module_length__gte=module_length,
max_roof_angle=45,
building_height=30,
importance_factor=1,
seismic=1.2,
zone=1,
profile='worst'
).order_by('snow', 'module_length', 'span')
return spans

现在你可以直接做,

Spans.get_spans(0, 85, 54)

关于带有 self 实例的 Django 模型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com