相关疑难解决方法(0)

在django中区分null = True,blank = True

当我们在django中添加数据库字段时,我们通常会写models.CharField(max_length=100, null=True, blank=True).同样是用ForeignKey,DecimalField等等.有什么基本的区别

  1. null=True 只要
  2. blank=True 只要
  3. null=True, blank=True

在相对于不同的(CharField,ForeignKey,ManyToManyField,DateTimeField)字段.使用1/2/3有哪些优点/缺点?

python django django-models

819
推荐指数
14
解决办法
22万
查看次数

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 = True

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

    class Meta:
        abstract = True
Run Code Online (Sandbox Code Playgroud)

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

class UserCustomDataField(CustomDataField):
    pass

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

    class Meta:
        unique_together=(('user','custom_field'),)
Run Code Online (Sandbox Code Playgroud)

这导致以下用途:

custom_field = UserCustomDataField.objects.create(name='zodiac', site=my_site) #probably created …
Run Code Online (Sandbox Code Playgroud)

python django dynamic django-models django-custom-manager

156
推荐指数
2
解决办法
6万
查看次数