python - 如何使此代码用于获取列表中的对象更短?
问题描述
我正在检索要添加到字典的数据库对象,但键不能重复,所以我这样做了:
carb1 = random.choice(carbs)
protein1 = random.choice(proteins)
carb2 = Food.objects.filter(category='Carbs').exclude(name=carb1.name)[0]
protein2 = Food.objects.filter(category='Protein').exclude(name=protein1.name)[0]
veg1 = random.choice(vegs)
veg2 = Food.objects.filter(category='Vegetables').exclude(name=veg1.name)[0]
meals = [carb1, protein1, carb2, protein2]
exclude_these = [o.name for o in meals]
carb3 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0]
protein3 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0]
veg3 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0]
meals.append(carb3)
meals.append(protein3)
meals.append(veg3)
exclude_these = [o.name for o in meals]
carb4 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0]
protein4 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0]
veg4 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0]
meals.append(carb4)
meals.append(protein4)
meals.append(veg4)
exclude_these = [o.name for o in meals]
carb5 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0]
protein5 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0]
veg5 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0]
meals.append(carb5)
meals.append(protein5)
meals.append(veg5)
exclude_these = [o.name for o in meals]
carb6 = Food.objects.filter(category='Carbs').exclude(name__in=exclude_these)[0]
protein6 = Food.objects.filter(category='Protein').exclude(name__in=exclude_these)[0]
veg6 = Food.objects.filter(category='Vegetables').exclude(name__in=exclude_these)[0]
但这似乎是实现我想要的代码的荒谬数量。
有什么办法可以缩短这个吗?
解决方案
看起来你想从你的食物表中检索 6 种碳水化合物、6 种蛋白质和 6 种蔬菜,而你并不关心它们是什么(你在查询中没有提供排序并取每个中的第一个)。除了第一个是随机的。也许您不在乎第一个是随机挑选的,或者您可能希望其余 5 个也被统一随机挑选?
以下是一些选项:
carb1, carb2, carb3, carb4, carb5, carb6 = tuple(
Food.objects.filter(category='Carbs')[:6]
)
与 portein 和 veg 类似。坦率地说,不要将变量命名为 carbN,只需将它们全部放在列表或元组中即可。carbs = Food....[:6]
如果名称列不是唯一的,并且您确实想要 6 个具有不同名称的碳水化合物,
carbs = Food.objects.filter(category='Carbs').distinct('name')[:6]
不同的列而不是整个记录在所有数据库后端都不起作用。它适用于postgres,但我认为它不适用于mysql。
如果你真的想要 6 种随机碳水化合物,你可以让数据库为你随机化。
carbs = Food.objects.filter(category='Carbs').order_by('?')[:6]
如果您的食物表很大,随机订购可能会出现一些性能问题。
推荐阅读
- c++ - 如何检索文件的共享模式?
- sql - 如何正确写出复杂的逻辑条件?
- linux - 如何根据错误关键字从日志文件中提取行?
- python - 如何并排遍历列表中的字符串元素?
- python - Sendgrid 使用 API 密钥进行身份验证
- javascript - office-js中的Excel函数解析
- artifactory - Artifactory 从 6.14.1 升级到 7.10.2:migrate.sh 找不到旧的 Artifactory 版本
- argo-workflows - 如何为 Argo Workflow DAG 中的每个步骤传递不同的参数值
- flexbox - Flexbox、uk-flex-left 和 uk-flex-right
- docusignapi - 签名后 HTML 文档缩小