灵活的数据库模型,用户可以在Django中定义额外的列到数据库表格
问题描述:
我正在尝试构建一个工具,它在简单的层面上试图分析如何购买公寓。 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迎刃而解了 - 我相信许多其他人会遇到这个问题已经
感谢
答
编辑:正如评论指出。在这种情况下,JSON字段是一个更好的主意。
简单。使用关系。
创建一个名为attributes的模型。
它将有一个属性,名称字段和值字段的外键。
喜欢的东西,
class Attribute(models.Model):
property = models.ForiegnKey(Property)
name = models.CharField(max_length=50)
value = models.CharField(max_length=150)
创建一个对象的每一个属性的所有自定义属性。
当使用数据库查询时,使用select_related
的prefetch_related
可以获得更快的响应,减少数据库操作。
这被称为实体属性值或EAV建模。使用JSONField是一个比这更好的选项,如果JSONField的列变得流行,你可以索引这些列。 –
我们用关系做了几个EAV实现。它起作用,它可以扩展,但是当它变得非常大时,它往往会变得压倒性的。我们已经开始研究JSON解决方案:https://github.com/zostera/django-jeaves – dyve