猿问

Django动态模型场

Django动态模型场

我在做一个多租应用程序中,一些用户可以定义自己的数据字段(通过管理)来收集表单中的其他数据并报告数据。后一位使JSONField不是一个很好的选择,因此我有以下解决方案:

class CustomDataField(models.Model):
    """
    Abstract specification for arbitrary data fields.
    Not used for holding data itself, but metadata about the fields.
    """
    site = models.ForeignKey(Site, default=settings.SITE_ID)
    name = models.CharField(max_length=64)

    class Meta:
        abstract = Trueclass CustomDataValue(models.Model):
    """
    Abstract specification for arbitrary data.
    """
    value = models.CharField(max_length=1024)

    class Meta:
        abstract = True

注意CustomDataField如何拥有ForeignKey到Site-每个站点将有不同的自定义数据字段集,但使用相同的数据库。然后,可以将各种具体数据字段定义为:

class UserCustomDataField(CustomDataField):
    passclass UserCustomDataValue(CustomDataValue):
    custom_field = models.ForeignKey(UserCustomDataField)
    user = models.ForeignKey(User, related_name='custom_data')

    class Meta:
        unique_together=(('user','custom_field'),)

这导致以下使用:

custom_field = UserCustomDataField.objects.create(name='zodiac', site=my_site) #probably created in the adminuser = User.
objects.create(username='foo')user_sign = UserCustomDataValue(custom_field=custom_field, user=user, data='Libra')user.
custom_data.add(user_sign) #actually, what does this even do?

但这感觉非常笨拙,特别是需要手动创建相关数据并将其与具体模型相关联。有没有更好的方法?

被先发制人抛弃的选项:

  • 自定义SQL以动态修改表.部分是因为这不会扩大规模,另一部分是因为这是一次过多的黑客攻击。
  • 无模式的解决方案,如NoSQL。我不反对他们,但他们还是不合适。最终这些数据

    类型,并且存在使用第三方报告应用程序的可能性。
  • 如上所述,JSONField不能很好地处理查询。


蝴蝶刀刀
浏览 457回答 3
3回答
随时随地看视频慕课网APP

相关分类

Python
我要回答