具有多种关系的模型

时间:2015-07-06 17:20:27

标签: django django-models

我有一个这样的模型:

class Property(models.Model):
    rsa = models.ForeignKey(settings.AUTH_USER_MODEL) #Real State Agency
    agents = models.ManyToManyField(Agent)
    title = models.CharField(max_length=250, blank=False, null=False, verbose_name=_('Title'))
    slug = AutoSlugField(populate_from='title', unique=True, db_index=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    country = models.ForeignKey(PropertyCountry, null=False)
    state = models.ForeignKey(PropertyState, null=False)
    city = models.ForeignKey(PropertyCity, null=False)
    neighborhood = models.CharField(max_length=250, default='')
    neighborhood_alias = models.CharField(max_length=250, blank=True, default='')
    address = models.CharField(max_length=150, blank=True, default='')
    phone = models.CharField(max_length=20, default='')
    contact_email = models.EmailField(max_length=250, default='')
    price = models.IntegerField(default=0, null=False)
    price_admin = models.IntegerField(default=0, null=False)
    area = models.IntegerField(default=0, null=False)
    private_area = models.IntegerField(blank=True, default=0, null=False)
    bedrooms = models.IntegerField(blank=True, default=0, null=False)
    bathrooms = models.IntegerField(blank=True, default=0, null=False)
    property_type = models.ForeignKey(PropertyType, null=True)
    type_offer = models.ForeignKey(OfferType, null=True)
    status = models.ForeignKey(Status, blank=True, null=True)
    antiquity = models.ForeignKey(YearsOld, blank=True, null=True)
    number_floors = models.IntegerField(default=1, blank=False, null=False)
    state_property = models.ForeignKey(StateProperty, null=True)
    comment = models.TextField(blank=True, default='', verbose_name=_('Comment'))
    parking_spaces = models.PositiveSmallIntegerField(blank=True, default=0, null=False)
    weather = models.ForeignKey(WeatherType, blank=True, null=True)
    stratus = models.IntegerField(default=-1, blank=True, null=False)
    address_view = models.ForeignKey(AddressView, null=True)

大多数外键都是这样的:

class PropertyType(models.Model):
    name = models.CharField(max_length=50, default='')
    id_something_a = models.IntegerField(default=-1, blank=False, null=False)
    id_something_b = models.IntegerField(default=-1, blank=False, null=False)

正如您所看到的,很多字段都是外键或许多字段。如果我想检索我的属性的所有数据,我需要很多连接,我认为最终可能会变慢。

作为替代方案,在这种情况下,我可以使用选择字段并在python中映射值(这些外键中的值不会经常更改)。

我的问题是:

  • 是否有其他方法可以对此进行建模,同时降低可能出现的性能损失?
  • 有什么需要关注的吗? (惩罚不够大,没有足够的外键/连接来引起重要的事情等)

1 个答案:

答案 0 :(得分:0)

我希望尽可能保持一切正常化,直到痛苦为止。然后我针对主要用例进行优化,根据需要进行去标准化。不要忘记你可以在这个问题上投入更多硬件并看到不错的结果。然而,这真的是一个创可贴。

如果您的联接在大型表之间,那么就有理由担心。我会尽量避免一次获取所有数据。缩小查询次数以缩短查询时间。但是,如果您正在进行数据转储,则需要时间。

基本上我的方法是保持架构上的声音,直到它们成为问题。然后优化所需的位置,使块加载,增加RAM / CPU /硬件。我已经在10GB范围内的数据集上使用了这种方法,其中有数百万个数据表。我从来没有一张超过五千万的桌子,所以我不能说出庞大的数据集。