码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-05-16 20:02:22      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

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 外键、多对多插入数据方法

标签:

原文地址:http://www.cnblogs.com/stefan-liu/p/5499023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!