Example of Django Adding and Updating a Database

  • 2021-07-18 08:13:58
  • OfStack

Put models. py here first


#models.py
class UserProfile(AbstractUser):
 '''
  Inheritance Django Adj. AbstractUser  And add two data content doubts to it 
 '''
 gender = models.CharField(max_length=6,choices=(('male',' Male '),('female',' Female ')),default='female',verbose_name=' Gender ')
 memo = models.TextField(null=True, blank=True,verbose_name=' Notes ')
 class Meta:
  verbose_name = ' User information '
  verbose_name_plural = verbose_name # Specifies what the complex form of the model is , If you do not specify Django Is automatically appended to the model name 1 A 's'
 
class UserTodo(models.Model):
 created_time = models.DateTimeField(default=datetime.now(),verbose_name=' Creation time ')
 user_id = models.ForeignKey(UserProfile,on_delete=models.C ASCADE) # Sets the foreign key, associated with the UserProfile Table 
 # models.CASCADE Indicates that if you delete a 1 User, all of the UserTodo It will also be deleted 
 ToDolist = models.CharField(max_length=255,verbose_name='todo')
 done = models.BooleanField(default=False,verbose_name=' Completion status ')
 class Meta:
  verbose_name = ' User self-increasing information '
  verbose_name_plural = verbose_name

1. Save data to a database (in views. py)

After completing model, run python manage. py makemigrations on Terminal to generate the database. You can then save

For databases without foreign keys:


from .models import UserProfile
from django.contrib.auth.hashers import make_password
user_profile = UserProfile()
user_profile.username = username
user_profile.email = email
user_profile.password = make_password(password) #make_password Yes django Bring your own to password Recoding technology, stored in the database 
user_profile.is_active = True # Judge whether the user is activated or not 
user_profile.save()

Database with foreign keys

1. First of all, the information of the associated database should be obtained. If it is a user, it is ID in the database

user_id = UserProfile. objects. get (username=request. user) # request. user indicates the user name currently logged in, and the background is actually the user name

2. Save to database


user_todo = UserTodo(ToDolist=todo,done=done,user_id=user_id,created_time=datetime.now())  When saved to the database, according to the user name id Save 
user_todo.save()

2. Update and query the database

The motivation is that when the user clicks on the X number on the web page, it updates done in the database and updates it to True.

1 started to think about updating according to id, but when there are more users, id is definitely different from id displayed on the web page.

After my hard thinking, the time to create todo is definitely different for each user, so you can update done according to the search available for created_time.

Just do it!

1. Query the 1 piece of data we want first

The user's todo is sorted by created_time when displayed on the web page, so it is sorted by created_time when updated, so there is no error.


user_id = UserProfile.objects.get(username=request.user) # Object of the currently logged-in user todo id (According to the background print, it is actually the user name) 
todo_query = UserTodo.objects.filter(user_email=user_id, done=False) # According to user_id , done Filter the database 
# In UserTodo Find out in the table user_id And under this user done=False Data of 
#todo_query The type of is <class 'django.db.models.query.QuerySet'>
todo_query = todo_query.order_by("created_time") #  Filter by end date in order from small to large. To sort from large to small, ("-created_time")

The result now is that we have all the done=False data for this user name and have finished sorting

The next step is to find the one piece of data we want


todo_dict = todo_query.values("created_time") # Pass by values , get created_time That of 1 Column data 

The type is still QuerySet, but there is only one kind of data, that is, all the data are created_time, then we can extract the data we want


time_dict[3]['created_time'] #QuerySet Middle grade 4 The name is created_time The data of the (sequence number from the 0 Start, so 3 Is the first 4 A) 3 Is the index of elements on a web page 

 Print print(time_dict[3]['created_time']) The result is: 2018-06-07 01:45:10.938825+00:00

The data query has been completed at this point.

2. Update the data

It's already a piece of cake hiahiahia. . .

According to the created_time queried above, find out the records that meet this 1 cteated_time under the current user (there must be only 1)


time_index = time_dict[id]['created_time'] #id For the elements on the web page passed from the front end id
User = UserTodo.objects.get(user_id=user_id,created_time=time_index)
User.done = True
User.save()

Done!


Related articles: