Python 灵活的数据库模型,用户可以在Django中为数据库表定义额外的列
我试图建立一个工具,在一个简单的层面上,试图分析如何购买一套公寓。DB=POSTGRES 因此,模型基本上是:Python 灵活的数据库模型,用户可以在Django中为数据库表定义额外的列,python,django,database,postgresql,Python,Django,Database,Postgresql,我试图建立一个工具,在一个简单的层面上,试图分析如何购买一套公寓。DB=POSTGRES 因此,模型基本上是: class Property(models.Model): address = CharField(max_length = 200) price = IntegerField() user = ForeignKey(User) # user who entered the property in the database #..
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,这个问题并没有很快得到解决——我相信很多其他人已经遇到了这个问题
谢谢
编辑:正如评论所指出的。在这种情况下,JSON字段是一个更好的主意
简单。使用关系
创建一个名为attributes的模型
它将具有属性的外键、名称字段和值字段
大概
class Attribute(models.Model):
property = models.ForiegnKey(Property)
name = models.CharField(max_length=50)
value = models.CharField(max_length=150)
为每个属性的所有自定义属性创建一个对象
当使用数据库查询时,使用以获得更快的响应,减少数据库操作。这称为实体属性值,或EAV建模。使用JSONField是一个更好的选择,如果JSONField的列变得流行,您可以对它们进行索引。它是有效的,它可以扩展,但当它变得非常大时,它往往变得势不可挡。我们已经开始研究JSON解决方案: