Python 如何缩短列表中对象的代码?
我正在检索要添加到dict的数据库对象,但密钥不能重复,所以我是这样做的:Python 如何缩短列表中对象的代码?,python,django,Python,Django,我正在检索要添加到dict的数据库对象,但密钥不能重复,所以我是这样做的: 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
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,只要将它们全部放在一个列表或元组中即可<代码>碳水化合物=食物….[:6]
如果名称列不唯一,并且您确实需要6个名称不同的碳水化合物
carbs = Food.objects.filter(category='Carbs').distinct('name')[:6]
在列上而不是整个记录上使用Distinct在所有数据库后端都不起作用。它在postgres中有效,但我认为它在mysql中不起作用
如果你真的想要6个随机碳水化合物,你可以让数据库为你随机
carbs = Food.objects.filter(category='Carbs').order_by('?')[:6]
如果您的食物表很大,随机订购可能会出现一些性能问题