ManyToMany associated django model to add, delete, query

 

models.py contents of the file:

from django.db import models

class person(models.Model):
    name = CharField(max_length=30)

class book(models.Model):
    auther = ManyToManyField(person)

P is assumed that a person object, b is a book objects:

# Add a related 
b.auther.add (the p-) 

# Remove Association 
b.auther.remove (the p-) 

# returns all authors 
b.auther.all () 

# reverse lookup, return all books written by this man, book is the anti the model name query 
p.book_set.all ()

 

If the model models.py contents of the file:

from django.db Import Models 

class Person (models.Model): 
    name = as CharField (MAX_LENGTH = 30 ) 

class Book (models.Model):
     # When a model is associated with more than one field, the parameters to be used to specify the table name related_name 
    = ManyToManyField auther (Person, the related_name = " auther " ) 
    translater = ManyToManyField (Person, the related_name = " translater " )

At this time, reverse lookup p.book_set.all () is not available, instead of

# Returns all of the books were written, book_set be replaced related_name specified in the table name 
p.auther.all () 

# returns all books that people translated 
p.translater.all ()

 

Guess you like

Origin www.cnblogs.com/zhenzi0322/p/11268779.html