我想要檢索最近添加的元素,如果根本沒有,分配一些默認值,如:的Django,過濾最近添加的元素
query = X.objects.filter(name="aa",type="b")[0]
if query:
resultname =query.name
resulttype = query.type
else:
resultname = "a default name"
resulttype = "a default type"
這是行不通的,因爲這將提高第一行query = X.objects.filter(name="aa",type="b")[0]
執行並且過濾的查詢列表爲空時會出現異常。
這不一定會獲取最近添加的元素。只是「QuerySet」的第一個元素。您必須在模型的某個字段中進行排序,例如'created_at'。 – 2010-02-04 10:07:33