Create a data table for demonstration
models.py: class Boy(models.Model): name = models.CharField(max_length=32, null=True) class Girl(models.Model): nick = models.CharField(max_length=32, null=True) class Love(models.Model): b = models.ForeignKey("Boy", null=True) g = models.ForeignKey("Girl", null=True)
A corresponding query boy girl boy table
method one
# RES = models.Boy.objects.filter (name = 'boy1'). First () # # Print (RES)
### Boy Object # ### records in a reverse lookup love # love_list = res.love_set. All ()
## <QuerySet [<Love: Love Object>, <Love: Love Object>]> # for obj in love_list: # ### forward lookup table girl Nick # Print (obj.g.nick)
Method Two
# res = models.Love.objects.filter(b__name='勾洋').all() # print(res) ## <QuerySet [<Love: Love object>, <Love: Love object>]> # for obj in res: # print(obj.g.nick)
Method Three
res = models.Love.objects.filter(b__name='勾洋').values("g__nick") print(res)
The above method is based on the third-many table to create our own terms associated with the two tables together to achieve positive check pegging
In django, we can generate a third table by ManyToManyField ()
在models.py下 class Boy(models.Model): name = models.CharField(max_length=32, null=True) g = models.ManyToManyField('Girl', null=True) class Girl(models.Model): nick = models.CharField(max_length=32, null=True)
increase
= models.Boy.objects.filter obj (name = 'boy1 ' ) .first () Print (obj)
# ==> Boy Object obj.g.add (. 3) obj.g.add (* [1,2] ) add two data relation table
Reset
obj = models.Boy.objects.filter(name='boy1').first()
obj.g.set ([4]) all relevant data obj clear association table and rewrites data list
Inquire
obj = models.Boy.objects.filter(name='boy1').first() res = obj.g.all() print(res)
#==》<QuerySet [<Girl: Girl object>, <Girl: Girl object>, <Girl: Girl object>]> for obj in res: print(obj.nick)
delete
obj = models.Boy.objects.filter(name='boy1').first() obj.g.clear()