Associated query

  • When defining a model class, you can specify three types of relationships, the most common being one-to-many, as in this case, book-hero, which is a one-to-many relationship
python manage.py shell
Copy the code
  • Query book 1
book=BookInfo.books.get(pk=1)
Copy the code
  • Get all heroes of book books
book.heroinfo_set.all()
Copy the code

  • Obtain hero number 4
hero=HeroInfo.objects.get(hbook_id=3)
Copy the code
  • Get the hero from the book
hero.hbook
Copy the code

Since the correlation

  • For data such as region information and classification information, the table structure is very similar. The amount of data in each table is very limited. In order to make full use of the massive data storage function of data tables, you can design a table with internal relational fields pointing to the primary key of the table, which is the self-association table structure
  • Open the booktest/models.py file and define the AreaInfo class
  • Note: The relational attribute uses self to refer to this class, requiring null and blank to be allowed to be null, because first-level data does not have a parent
Class AreaInfo(models.Model): Atitle = models.charfield (max_length=30)# name aParent= Models.foreignKey ('self',null=True,blank=True)# relationCopy the code
  • The migration
python manage.py makemigrations
python manage.py migrate
Copy the code

  • Open the mysql command line and import data
source areas.sql
Copy the code
  • Open the booktest/views.py file and define the view area
from models import AreaInfo ... Def area(request): area = AreaInfo.objects.get(pk=440100) return render(request, 'booktest/area.html', {'area': area})Copy the code
  • Open the booktest/urls.py file and create a new URL
urlpatterns = [
    ...
    url(r'^area/$', views.area),
]
Copy the code
  • In the Templates /booktest directory, create a new area.html file
< HTML > <head> <title> region </title> </head> <body> Current region: {{area.atitle}} <hr/> Parent region: {{area.aparent.atitle}} <hr/> Parent region: {{area.aparent.atitle}} <hr/> Parent region: {{area.aparent.atitle}}  <ul> {%for a in area.areainfo_set.all%} <li>{{a.atitle}}</li> {%endfor%} </ul> </body> </html>Copy the code
  • Running server
python manage.py runserver
Copy the code

Note: there may be some bugs in the case, as well as a problem with the Django version that matches the Python version. If there are any problems, please advise