Django 外键多对多插入数据方法

Posted Stefan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django 外键多对多插入数据方法相关的知识,希望对你有一定的参考价值。

models.py

class UserInfo(models.Model):
    username = models.CharField(max_length=64,db_column=‘username‘)
    passwd = models.CharField(max_length=64,db_column=‘password‘)
    register_date = models.DateTimeField(max_length=32,db_column=‘register_date‘)
    last_login_date = models.DateTimeField(max_length=32,db_column=‘last_login_date‘,null=True)

    class Meta:
        app_label = ‘simple‘
        db_table = ‘user_info‘

class ServerInfo(models.Model):
    hostname = models.CharField(max_length=32,db_column=‘hostname‘)
    port = models.IntegerField(max_length=32,db_column=‘port‘)
    status = models.CharField(max_length=32,db_column=‘status‘)

    class Meta:
        app_label = ‘simple‘
        db_table = ‘server_info‘

class Publisher(models.Model):
    name = models.CharField(max_length=32)
    address = models.CharField(max_length=32)
    state = models.CharField(max_length=32)
    nation = models.CharField(max_length=32)
    website = models.URLField(max_length=32)

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

class Book(models.Model):
    title = models.CharField(max_length=32,unique=True)
    author = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    pubDate = models.CharField(max_length=32)

views.py

def addBook(request):
    if request.method == ‘POST‘:
        print("进入addbook post")
        print(request.POST)
        name = request.POST[‘name‘]
        author = request.POST.getlist(‘author‘)# 当获取多个数值的时候,使用getlist
        publisher = request.POST[‘publisher‘]
        p1 = Publisher.objects.get(id=publisher)#先在publisher表中查询出前端选中出版社对应的对象
        date = request.POST[‘publisherDate‘]
        b1 = Book(title=name,publisher=p1,pubDate=date)
        b1.save()#普通插入的数据和外键插入的数据需要先save()
        b1 = Book.objects.get(title=name)#查出书名对象,也就是获取要插入的多对多数据项
        if len(author) == 1:
            b1.author.add(author[0])#多对多使用add方法进行插入
            b1.save()
            return redirect("/displayBook/")
        elif len(author) == 0:#当用户没有选中作者
            return render(request,‘addBook.html‘,{"status":"添加出版社失败,没有选择作者"})
        else:#循环插入用户选中的多个作者
            for person in author:
                b1.author.add(person)#多对多使用add方法进行插入
            b1.save()
            return redirect("/displayBook/")
    print("进入addbook get")  #用户从库中获取页面可选的内容,get请求
    bookList = Book.objects.all()
    publisherList = Publisher.objects.all()
    authorList = Author.objects.all()
    print(bookList,publisherList,authorList)
    return render(request, ‘addBook.html‘,{‘books‘:bookList,
                                           ‘publishers‘:publisherList,
                                           ‘authors‘:authorList})

前端页面:

{% block head-menu %}
    <table border=1 style="margin-left:13%;margin-top: 3%;height: 30px;width: 1000px">
        <tr >
            <td>书名</td>
            <td>作者</td>
            <td>出版社</td>
            <td>出版日期</td>
        </tr>
        {% for book in books %}
            {% if forloop.counter|divisibleby:"2" %}
                <tr style="background-color: skyblue;">
                    <td>{{ book.title }}</td>
                    <td>{% for authorObj in book.author.select_related %} {{ authorObj.first_name }} {{ authorObj.last_name }} {% endfor %}</td>
                    <td>{{ book.publisher.name }}</td>
                    <td>{{ book.pubDate }}</td>
                </tr>
                </tr>
                </tr>
            {% else %}
                <tr style="background-color: salmon;">
                    <td>{{ book.title }}</td>
                    <td>{% for authorObj in book.author.select_related %} {{ authorObj.first_name }} {{ authorObj.last_name }} {% endfor %}</td>
                    <td>{{ book.publisher.name }}</td>
                    <td>{{ book.pubDate }}</td>
                </tr>
            {% endif %}
        {% endfor %}
    </table>
    <a href="/backend/"><button type="button" class="btn btn-primary btn-sm" style="margin-left: 43%;margin-top: 10%">返回</button></a>
{% endblock %}

以上是关于Django 外键多对多插入数据方法的主要内容,如果未能解决你的问题,请参考以下文章

django数据库操作-增删改查-多对多关系以及一对多(外键)关系

转: django数据库操作-增删改查-多对多关系以及一对多(外键)关系

Django 之 ORM表之间的外键关联与多对多

django 插入外键值思路

在 Django 中插入多对多对象的正确方法?

具有外键和多对多关系的 Django 模型与同一模型