XIV learning Django database table design: many to many, one to one, one to many

A-many table design, ManyToManyField associated fields.

 

Book and Author Relations: a book can have multiple authors, an author can publish more than one book, it is many-mode

1.1 models.py Code:

class Author(models.Model):

    """作者"""

    name = models.CharField(max_length=20,verbose_name="作者")
    mail = models.CharField(max_length=20,verbose_name="邮箱")
    address = models.CharField(max_length=50,verbose_name="籍贯")
    mobile = models.CharField(max_length=11,verbose_name="手机号")

    class Meta:

        verbose_name_plural = "作者"

    def __str__(self):

        return self.name


class Book(models.Model):

    '''
    Book Information
    '''

    book_name = models.CharField(max_length=100,verbose_name="书名")

    # -Many 
    auth = models.ManyToManyField (Author, verbose_name = " author " )

    class Meta:

        verbose_name_plural = "书籍"

    def __str__(self):

        return self.book_name

1.2 execute python manage.py makemigrations vote and python manage.py migrate

1.3 admin.py registration

class ControlAuthor(admin.ModelAdmin):

    list_display = ['name','mail','address','mobile']

class ControlBook(admin.ModelAdmin):

    list_display = [ ' BOOK_NAME ' , ' book_auth ' ]
     
# define a method of traversing the auth book, and then returns with a list
DEF book_auth (Self, obj): return [a.name for a in obj.auth.all()] admin.site.register(models.Author,ControlAuthor) admin.site.register(models.Book,ControlBook)

1.4 browser to access the results:

 

 After completion of the book, the database will generate a table-many relationship

 

Guess you like

Origin www.cnblogs.com/chushujin/p/12533851.html