【问题标题】:Flexible database models for users to define extra columns to database tables in Django灵活的数据库模型供用户在 Django 中为数据库表定义额外的列
【发布时间】:2017-07-29 15:44:43
【问题描述】:

我正在尝试构建一个简单的工具来尝试分析如何购买公寓。 DB = POSTGRES

所以模型基本上是:

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()       

如何为用户提供这样的灵活性?他们应该能够通过这些自定义字段对自己的行(在属性表中)进行排序、过滤和查询。我现在能想到的唯一选择是 JSONField Postgres 字段

有什么建议吗?我很惊讶这在 Django 中没有轻易解决 - 我相信很多其他人已经遇到过这个问题

谢谢

【问题讨论】:

    标签: python django database postgresql


    【解决方案1】:

    编辑:正如 cmets 指出的那样。在这种情况下,JSON 字段是一个更好的主意。

    简单。使用关系。

    创建一个名为属性的模型。

    它将有一个属性的外键、一个名称字段和一个值字段。

    类似的,

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

    为属性的所有自定义属性分别创建一个对象。

    使用数据库查询时,请使用prefetch_related 中的select_related 以获得更快的响应,更少的数据库操作。

    【讨论】:

    • 这称为实体属性值或 EAV 建模。使用 JSONField 是比这更好的选择,如果 JSONField 的列变得流行,您可以索引它们。
    • 我们已经用关系完成了一些 EAV 实现。它有效,它可以扩展,但是当它变得非常大时,它往往会变得不堪重负。我们已经开始研究 JSON 解决方案:github.com/zostera/django-jeaves
    猜你喜欢
    • 2018-01-09
    • 2020-08-17
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多