Models and Database Access in Django—Clough Dynamics of Structures

9.1 Related Objects

In Chapter 4, we defined the following models:

from django.db import models  
class Publisher(models.Model):  
    name = models.CharField(max_length=30)  
    address = models.CharField(max_length=50)  
    city = models.CharField(max_length=60)  
    state_province = models.CharField(max_length=30)  
    country = models.CharField(max_length=50)  
    website = models.URLField()  

    def __str__(self):  
        return self.name  

class Author(models.Model):  
    first_name = models.CharField(max_length=30)  
    last_name = models.CharField(max_length=40)  
    email = models.EmailField()  

    def __str__(self):  
        return '%s %s' % (self.first_name, self.last_name)  

class Book(models.Model):  
    title = models.CharField(max_length=100)  
    authors = models.ManyToManyField(Author)  
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)  
    publication_date = models.DateField()  

    def __str__(self):  
        return self.title  

We know accessing a specific column in the database is straightforward. For instance, to view the title of the book with ID 50, you can use the following commands:

>>> from mysite.books.models import Book  
>>> b = Book.objects.get(id=50)  
>>> b.title  
'The Django Book'  
pdf 文件大小:7.34MB