我遇到了一個複雜的查詢,試圖使用Django的ORM。複雜查詢(django ORM或SQL)
models.py
class Product(models.Model):
deprecated = models.ForeignKey(SpecialVersion, null=True)
class Version(models.Model):
compatible_from = models.ForeignKey(SpecialVersion)
product = models.ForeignKey(Product)
class SpecialVersion(models.Model):
version = models.ForeignKey(Version, null=True)
order = models.IntegerField()
這樣做的主旨在於,產品有多個版本。其中一些版本是「特殊的」 - 我們通過將SpecialVersion對象指向「特殊」版本對象來跟蹤此情況。當我們創建一個非特殊版本時,它必須指明與SpecialVersion的兼容性。也就是從compatible_from指定的SpecialVersion開始。產品可能會在某個特定版本中被棄用。
現在,我希望能夠找到適當的產品給予一定的SpecialVersion。換句話說,我想獲得所有Product對象,其中有一個SpecialVersion版本在我的給定SpecialVersion下面。此外,產品不推薦使用的SpecialVersion必須爲null,如果不爲null,則必須低於給定的SpecialVersion。
TL; DR: 選擇產品中給定的SpecialVersion位於最低的compatible_from SpecialVersion和棄用的SpecialVersion(如果存在)之間的範圍內的所有產品。
編輯:例子。
商品
ID |已棄用
0 |無
1 | 2
版本
id | prd | compat
0 | 0 | 1
1 | 0 | 2
2 | 1 | 2
SpecialVersions
id | ver | ord
0 |空| 1
1 |空| 2
2 |空| 3
3 |空| 4
與SpecialVersion的兼容性查詢將不返回任何產品,因爲沒有任何產品的版本指定的兼容性如此低。 compat w/SpecialVersion的查詢將返回所有產品,因爲它們都分別具有從SpecialVersion id = 1和id = 2開始的兼容性。最後,與SpecialVersion的compat查詢將僅返回產品id = 0,因爲雖然兩種產品都有足夠低的SpecialVersion compat,但第二種產品已被棄用,用於SpecialVersions及更高版本。
你能提供行,你會基於一個例子請求希望選擇一些虛假的數據和說明了什麼? – Stieffers 2012-08-06 16:30:42
當然。給我一點時間。 – guywhoneedsahand 2012-08-06 16:36:37
我使SpecialVersions有一個空版本字段,因爲那一點沒關係。 – guywhoneedsahand 2012-08-06 16:52:56