我有一个模特:
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_name
,cert_password
和key_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
答案 0 :(得分:4)
您可以一次更新GenerateCertificate
模型的所有对象
data_dict = {'cert_name': '', 'cert_password': '', 'key_name': ''}
GenerateCertificate.objects.all().update(**data_dict)