更新配置文件Django中所有用户的属性

时间:2018-08-05 17:54:48

标签: django django-models django-admin

我有一个模特:

class GenerateCertificate(models.Model):

    username = models.OneToOneField(User, on_delete=models.CASCADE)
    cert_name = models.CharField(
        max_length=15,
        default='',
        blank=True,
        editable=False)
    cert_password = models.CharField(
        max_length=20,
        default='',
        blank=True,
        editable=False)
    key_name = models.CharField(
        max_length=15,
        default='',
        blank=True,
        editable=False)

    def __unicode__(self):
        return unicode(self.username)

我想更新属性cert_namecert_passwordkey_name,并在所有这些属性中设置值''。通过以下操作,一个用户很容易做到这一点:

def DeleteUserData(self, request, queryset):
    for qs in queryset:
        username = str(qs.username)
        #get user data from database
        user = GenerateCertificate.objects.get(username__username=username)
        keyname = user.key_name
        certname = user.cert_name

        GenerateCertificate.objects.filter(username__username=username).update(
            cert_name='')
        GenerateCertificate.objects.filter(username__username=username).update(
            cert_password='')
        GenerateCertificate.objects.filter(username__username=username).update(
            key_name='')

但是如何一次对数据库中的所有用户执行此操作?

我正在使用Django 2.0.6和Python 3.5

1 个答案:

答案 0 :(得分:4)

您可以一次更新GenerateCertificate模型的所有对象

data_dict = {'cert_name': '', 'cert_password': '', 'key_name': ''}
GenerateCertificate.objects.all().update(**data_dict)