简体   繁体   English

在Django模型的空白/空False外键字段中填充默认值

[英]fill with a default value in a blank/null False foreignkey field in Django model

class MyModel(models.Model):
     field1 = models.ForeignKey('AnotherModel', null=False, blank=False)
     field2 = #its a choice field
     # some more fields

What I want is to fill the field1 with a default value if field2 is equal to some specific value (from choice tuple). 我想要的是如果field2等于某个特定值(来自选择元组),则使用默认值填充field1

I gave it a try by overriding the save() method but I wasn't successful. 我通过重写save()方法进行了尝试,但未成功。

def save(self, *args, *kwargs):
   if self.field2 == 'some-specific-value':
      self.field1 = 'some-default-value or a dummy object id?'

For other values of choice field ( field2 ) user has to provide a value but as mentioned above, for a specific value we will fill with default word/string. 对于选择字段( field2 )的其他值,用户必须提供一个值,但是如上所述,对于特定值,我们将使用默认单词/字符串填充。

I even tried to use signal pre_save , pre_init , post_init but no success 我什至尝试使用信号pre_savepre_initpost_init但是没有成功

@receiver(post_init, sender=MyModel)
def populate_field1(sender, instance, *args, **kwargs):
    print 'in signal'
    if instance.field2 == 'some-specific-value':
          instance.field1 = 'some-default-value'

How can I do this? 我怎样才能做到这一点?

Cleaning is where I would do that if I were you, but I've also seen folks use @property and @func.setter to have it add functionality - so if I set field1, the setter also sets field2 accordingly as it's assigned. 如果您是我,将执行清洁操作,但我也看到人们使用@property和@ func.setter为其添加功能-因此,如果我设置了field1,则设置器还将在分配它时相应地设置field2。

You can do this on cleaning - so if the field is blank=True but not null=True, you can save the field, and cleaning will be where the logic gets executed. 您可以在清理时执行此操作-因此,如果该字段为blank = True但不是null = True,则可以保存该字段,清理将在逻辑执行的地方进行。 This will allow you to save() the model and pass validation (Since blank=True, I can call the save method without erroring, or manually setting it), and my cleaning ensures that the null=False condition is still met by assigning before saving is complete. 这将使您可以保存()模型并通过验证(由于blank = True,我可以调用save方法而不会出错,也可以手动设置它),并且我的清理工作可以确保null = False条件仍然可以通过以下方式分配:保存完成。

class MyModel(models.Model):
     field1 = models.ForeignKey('AnotherModel', null=False, blank=False)
     field2 = #its a choice field
     # some more fields

     def clean(self):
         if self.field2.field == 'value':
             self.field1 = AnotherModel.logic.to.get_the_right_(one)
         else:
             self.field1 = AnotherModel.some_default(value)

Here's an example where I did something similar but with less dependencies: 这是一个示例,其中我执行了类似的操作但相关性较少:

class Domain(models.Model):
    class Meta:
        ordering = ['domain_name']

    domain_id = models.CharField(max_length=255, unique=True, blank=True)
    domain_name = models.CharField(max_length=255, unique=True)
    domain_arrays = models.ManyToManyField('Array', blank=True)

    def __str__(self):
        return self.domain_name

    def clean(self):
        self.domain_id = self.domain_name.lower().replace('.', '_')
        self.domain_name = self.domain_name.lower()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM