簡體   English   中英

如何使此代碼用於獲取列表中的對象更短?

[英]How can I make this code for getting objects for my list shorter?

我正在檢索要添加到字典的數據庫對象,但鍵不能重復,所以我這樣做了:

    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]

如果您的食物表很大,隨機訂購可能會出現一些性能問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM