class Line(models.Model):
_name = "line"
line1.quantity = 5
line2.quantity = 8
line3.quantity = 3
def count_line(self):
for line in self:
# i need to count all lines and print that line in the end #that has least quantity.
它更像是伪代码,我只想知道如何做到这一点。
答案 0 :(得分:1)
如果您有一个包含所有行的列表,则可以执行以下操作:
line_list.sort(key=lambda x: x.quantity, reverse=False)
less_quantity = line_list[0].quantity
答案 1 :(得分:1)
由于对quantity
属性没有任何限制,因此此代码应处理边缘情况。请注意,它根据需要打印quantity
最小的行,并返回总行数。如果没有行,则打印输出为None
,并返回数字0
。如果quantity
有一个下限,则可以简化代码。
def count_line(self):
"""Count all lines, print that line in the end that has least
quantity, and return the number of lines."""
counter = 0
result = None
for counter, line in enumerate(self):
if result is None or result.quantity > line.quantity:
result = line
print(result)
return counter