2017-07-29 28 views
1

我正在嘗試構建一個工具,它在簡單的層面上試圖分析如何購買公寓。 DB = POSTGRES靈活的數據庫模型,用戶可以在Django中定義額外的列到數據庫表格

因此模型主要是:

class Property(models.Model): 
    address = CharField(max_length = 200) 
    price = IntegerField() 
    user = ForeignKey(User)  # user who entered the property in the database 
    #.. 
    #.. 
    # some more fields that are common across all flats 



    #However, users might have their own way of analysing 

    # one user might want to put 

    estimated_price = IntegerField() # his own estimate of the price, different from the zoopla or rightmove listing price 
    time_to_purchase = IntegerField() # his own estimate on how long it will take to purchase 


    # another user might want to put other fields 
    # might be his purchase process requires sorting or filtering based on these two fields 

    number_of_bedrooms = IntegerField() 
    previous_owner_name = CharField()  

如何給這樣flexiblity給用戶?他們應該能夠通過這些自定義字段對它們自己的行進行排序,過濾和查詢(在Property表中)。我現在唯一能想到的選擇是JSONField Postgres字段

有什麼建議嗎?我很驚訝這不是在Django迎刃而解了 - 我相信許多其他人會遇到這個問題已經

感謝

回答

0

編輯:正如評論指出。在這種情況下,JSON字段是一個更好的主意。

簡單。使用關係。

創建一個名爲attributes的模型。

它將有一個屬性,名稱字段和值字段的外鍵。

喜歡的東西,

class Attribute(models.Model): 
    property = models.ForiegnKey(Property) 
    name = models.CharField(max_length=50) 
    value = models.CharField(max_length=150) 

創建一個對象的每一個屬性的所有自定義屬性。

當使用數據庫查詢時,使用select_relatedprefetch_related可以獲得更快的響應,減少數據庫操作。

+1

這被稱爲實體屬性值或EAV建模。使用JSONField是一個比這更好的選項,如果JSONField的列變得流行,你可以索引這些列。 –

+1

我們用關係做了幾個EAV實現。它起作用,它可以擴展,但是當它變得非常大時,它往往會變得壓倒性的。我們已經開始研究JSON解決方案:https://github.com/zostera/django-jeaves – dyve

相關問題