Introduction of Several Uses of Django model update

  • 2021-07-22 10:00:54
  • OfStack

model update General Usage

Suppose our table structure is like this


class User(models.Model):
 username = models.CharField(max_length=255, unique=True, verbose_name=' User name ')
 is_active = models.BooleanField(default=False, verbose_name=' Activation status ')

Then we can modify the user name and status in the following two ways:

Method 1:


User.objects.filter(id=1).update(username='nick',is_active=True)

Method 2:


_t = User.objects.get(id=1)
_t.username='nick'
_t.is_active=True
_t.save()

Method 1 is suitable for updating a batch of data, similar to the mysql statement update user set username = 'nick' where id = 1

Method 2 is suitable for updating one piece of data, and can only update one piece of data. It is recommended to use this method when only one piece of data is updated. In addition, this method has one advantage. Let's look at it next

Update with auto_now attribute field

We usually add three default fields to the table

Self-added ID, this django has been added by default, just like the table building statement above. Although only two fields, username and is_active, are written, there will also be a default self-added id field after the table is built

Creation time, which is used to identify the creation time of this record. It has the attribute auto_now_add, and the current time will be automatically filled into this field when creating the record

Modification time, used to identify the last modification time of this record, with auto_now attribute. When the record changes, fill in the current time to this field

A table structure like the one below


class User(models.Model):
 create_time = models.DateTimeField(auto_now_add=True, verbose_name=' Creation time ')
 update_time = models.DateTimeField(auto_now=True, verbose_name=' Update time ')
 username = models.CharField(max_length=255, unique=True, verbose_name=' User name ')
 is_active = models.BooleanField(default=False, verbose_name=' Activation status ')

When a table has a field with the auto_now attribute and you want it to be updated automatically, you must use the update of method 2 above, otherwise the auto_now field will not be updated, that is:


_t = User.objects.get(id=1)
_t.username='nick'
_t.is_active=True
_t.save()

json/dict Type Data Update Field

At present, the mainstream web open mode pays attention to the separation of front and back ends. After separation, the data format of front and back end interaction mostly uses the general jason type, so how to update json format data to the database conveniently with the least code? The following two methods can also be used:

Method 1:


data = {'username':'nick','is_active':'0'}
User.objects.filter(id=1).update(**data)
Again, this method does not automatically update the value of the field with the auto_now attribute Usually we add an asterisk (*) before the variable to indicate that the variable is a tuple/list, and add two asterisks to indicate that the parameter is a dictionary

Method 2:


data = {'username':'nick','is_active':'0'}
_t = User.objects.get(id=1)
_t.__dict__.update(**data)
_t.save()

Method 2 and Method 1 also do not automatically update the value of the auto_now field

Note that an dict method is used here

Method 3:


_t = User.objects.get(id=1)
_t.role=Role.objects.get(id=3)
_t.save()

ForeignKey Field Update

If we have Foreignkey foreign keys in our table, how should we update them?


class User(models.Model):
 create_time = models.DateTimeField(auto_now_add=True, verbose_name=' Creation time ')
 update_time = models.DateTimeField(auto_now=True, verbose_name=' Update time ')
 username = models.CharField(max_length=255, unique=True, verbose_name=' User name ')
 is_active = models.BooleanField(default=False, verbose_name=' Activation status ')
 role = models.ForeignKey(Role, on_delete=models.CASCADE, null=True, verbose_name=' Role ')

Method 1:


User.objects.filter(id=1).update(role=2)
The simplest way is to directly set the role field to 1 id Of course, you can also update with dict as a parameter:

User.objects.filter(id=1).update(username='nick',is_active=True)
0

Method 2:


User.objects.filter(id=1).update(username='nick',is_active=True)
1 You can also assign 1 instance to role Of course, you can also update with dict as a parameter:

User.objects.filter(id=1).update(username='nick',is_active=True)
2

Method 3:


_t = User.objects.get(id=1)
_t.role=Role.objects.get(id=3)
_t.save()
Note: role here must be assigned to an object, and id cannot be written, otherwise an error will be reported as "User. role" must be a "Role" instance When updating with dict as a parameter, there is another difference, as follows:

User.objects.filter(id=1).update(username='nick',is_active=True)
4 The Foreignkey foreign key must be appended with ` _id `, for example: {'role_id': 3} role_id must be followed by 1 id (int or str type), not role instance

ManyToManyField Field Update

What is the effect of updating if we have ManyToManyField fields in our table?


User.objects.filter(id=1).update(username='nick',is_active=True)
5

m2m Update: The m2m field has no direct update method and can only be updated by emptying and adding


User.objects.filter(id=1).update(username='nick',is_active=True)
6

add (): m2m field adds 1 value, when there are more than one value available list, refer to the above example

_t.groups.add(2)
_t.groups.add(Group.objects.get(id=2))

remove (): m2m field removes 1 value, when there are more than one value available list, refer to the above example

_t.groups.remove(2)
_t.groups.remove(Group.objects.get(id=2))

clear (): Empty the value of the m2m field


Related articles: