![](/img/trans.png)
[英]How to save a random item returned from QuerySet. Django, Python
[英]Django searching for a string match in a list of dictionary which is returned from queryset.
我的view.py中有类似的内容
def calculateMark(mobile_a, mobile_b):
#variables
mobile_a = mobile_a
mobile_b = mobile_b
results_a = []
results_b = []
record_a = TechSpecificationAdd.objects.filter(mobile_name=mobile_a).values()
record_b = TechSpecificationAdd.objects.filter(mobile_name=mobile_b).values()
results_a += record_a
results_b += record_b
record_a = record_a[0]
record_b = record_b[0]
if 'Android' in record_a['os']:
os_mark_a = 8.9
elif 'Android' in record_b['os']:
os_mark_b = 8.9
elif 'iOS' in record_a['os']:
os_mark_a = 14
if 'iOS' in record_b['os']:
os_mark_b = 14
else:
os_mark_a = 1
os_mark_b = 1
computeMark函数将为手机计算一个标记。 一切正常,但要进行操作系统(os)测试。 它总是返回else块。
问题是如何在我的record ['os']字段中搜索类似“ ios”的字符串?
如果我错了,请纠正我,但我认为您的问题是以下行中的if
:
if 'iOS' in record_b['os']:
作为该代码在比其他的iOS每一种情况下的结果record_b
,既os_mark_a
和os_mark_b
将被设置为1
。 即使之前将它们设置为另一个值,它们也将被1
覆盖。 要更正此特定问题,请将行更改为:
elif 'iOS' in record_b['os']:
我还有其他奇怪的事情:
在大多数情况下,您只设置了os_mark_b
或os_mark_a
的一个,而另一个未设置。 例如,您可以通过将两者都设置为默认值来更正此问题。
您不需要使用values()
将值加载到字典中-只需使用.get()
即可直接使用结果对象。 除其他好处外,这将完全消除第6、7、10、11、12、13行。
A和B的计算似乎完全分开。 似乎更明智的做法是创建一个较小的方法,用calucaltes标记单个对象。
您的方法不返回任何内容。 我认为这仅仅是因为这是一个简化的示例。
以下代码是关于什么的? 那什么也没做...
mobile_a = mobile_a mobile_b = mobile_b
更新:没有这些问题的代码示例:
def calculateMark(mobile):
record = TechSpecificationAdd.objects.get(mobile_name=mobile)
if 'Android' in record.os:
return 8.9
if 'iOS' in record.os:
return 14
return 1
更新2:另外,由于到目前为止我们已经在改进此代码方面做过很多工作-这不应该是一个单独的函数,而应该是TechSpecificationAdd
对象上的方法。
class TechSpecificationAdd(models.Model):
# some fields
def calculateMark(self):
if 'Android' in self.os:
return 8.9
if 'iOS' in self.os:
return 14
return 1
然后,您将在代码中使用以下代码:
record = TechSpecificationAdd.objects.get(mobile_name=mobile)
mark = record.calculateMark()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.