Here is an example to illustrate:
Create a many-to-many relationship table
First, you can create a model:
There are two classes here: the role People and the nickname Nickname. A person can have multiple nicknames, and similarly, a nickname may be shared by multiple people. So they are many-to-many relationship.
Here we declare ManyToManyField in Nickname. (it can also be changed to declare in People)
class People(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField()
class Nickname(models.Model):
title = models.CharField(max_length=50)
people = models.ManyToManyField(People)
This will generate three tables: role table, nickname table, role_nickname association table.
data query
Here, the query is performed in two cases of whether the model has a ManyToManyField (similar to modification and addition):
People table:
There is no ManyToManyField in the model, so a method similar to reverse query: table name (lowercase)_set is required for association.
class PeopleView(View):
def get(self,request):
temp = People.objects.all()
aimlist = []
for i in temp:
aimlist.append({
"name":i.name,
"age": i.age,
"nickname":list(i.nickname_set.all().values())
})
return JsonResponse({"aimlist":aimlist})
Nickname table:
For the existence of ManyToManyField in the model:
class NicknameView(View):
def get(self,request):
temp = Nickname.objects.all()
aimlist = []
for i in temp:
aimlist.append({
"title":i.title,
"nickname":list(i.people.all().values())
})
return JsonResponse({"aimlist":aimlist})
data addition
Many-to-many attributes are usually data in the form of a list, which stores ids, such as [1,2,3],
It can be added one by one through the add() method by looping through it.
def post(self,request):
data = json.loads(request.body)
newpeople = People.objects.create(name=data['name'],age=data['age'])
for i in data['nickname']: #传递的是存放id的数组,如[1,2,3]
newpeople.nickname_set.add(i)
#newpeople.people.add(i)
return JsonResponse({"code": 200})
data modification
First find the data to be modified by id, and modify its other attributes;
Then delete all the fields associated with the modified data in the association table, and add them one by one.
def put(self,request):
data = json.loads(request.body)
aimpeople = People.objects.get(id=data["id"])
aimpeople.name = data['name']
aimpeople.age = data['age']
aimpeople.nickname_set.clear() #先清空关联表中的相关数据,再遍历列表重新添加。
for i in data['nickname']:
aimpeople.nickname_set.add(i)
aimpeople.save()
return JsonResponse({"code": 200})
data deletion
This is very simple, just delete it normally, and the associated table will change automatically.
def delete(self,request):
aimid = request.GET.get("id")
aimpeople = People.objects.get(id=aimid)
aimpeople.delete()
return JsonResponse({"code": 200})
The above is the whole content of many-to-many table related operations in django, I hope it will be helpful to you^_^