我正在尝试构建一个工具,在简单的层面上,尝试分析如何购买公寓。 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中并不容易解决 - 我相信很多其他人会遇到这个问题
由于
答案 0 :(得分:1)
编辑:正如评论所指出的那样。在这种情况下,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
来获得更快的响应,减少数据库操作。