在Django中使用** dict作为create / update_or_create方法的参数-不一致的异常

我有一个像这样的字典:

profile_data={'trial_duration': 0,'tac_agreed': True,'email': 'blahblah@gmail.com','signup_method': 'google','social_id': '2343432432','social_platform': 'google','name': 'blahblah tester'}

我想使用update_or_create方法将此字典映射到两个不同的模型对象。但是,Django处理此问题的方式似乎有些矛盾。

我有一个社交信息模型:

class SocialInformation(models.Model):

    social_id = models.CharField(max_length=256,blank=True,null=True)
    social_platform = models.CharField(max_length=256,choices=SOCIAL_PLATFORM_CHOICES,default='',null=True)

当我使用以下行时,它会无例外地执行并且值将按预期进行映射,即使 profile_data 字典中的大多数项目也不是 SocialInformation 上的字段em>模型,则映射只会忽略不相关的映射,并采用相关的映射。

social_info,created = SocialInformation.objects.update_or_create(defaults={**profile_data})

但是,当我对不同的模型执行相同的操作时,配置文件:

class Profile(models.Model):


    owner = models.OneToOneField('auth.User',primary_key=True,on_delete=models.CASCADE)
    name = EncryptedCharField(max_length=200,null=True)
    email = models.EmailField(blank=True)
    trial_duration = models.IntegerField(default=7)
    signup_method = models.CharField(max_length=256,choices=SINGUP_METHOD_CHOICES,blank=True)

etc. etc.

如果我执行同一行:

profile,created = Profile.objects.update_or_create(owner=user,defaults={**profile_data})

我收到以下错误:

FieldError: Invalid field name(s) for model Profile: 'social_id','social_platform'.

为什么它不像 SocialInformation 查询那样忽略 Profile 模型中没有的字段?

gaoboxingf 回答:在Django中使用** dict作为create / update_or_create方法的参数-不一致的异常

不是因为模型不同,而是因为在一种情况下更新对象,而在另一种情况下创建对象。

在第一个示例中,它正在更新对象,因此非字段are silently ignored

在第二个示例中,它是trying to create the object,它不允许使用无效的字段名称。

顺便说一句,SocialInformation.objects.update_or_create(defaults={**profile_data})在我看来是错误的。您无需进行过滤即可找到要更新的SocialInformation。看起来您的数据库中可能只有一个SocialInformation,并且始终在更新该SocialInformation。如果您手动添加了另一个MultipleObjectsReturned(例如,通过Django管理员),那么我希望该行开始引发flex-direction:row;异常。

本文链接:https://www.f2er.com/3096192.html

大家都在问