django一对多下拉列表

本文探讨了在Python Django框架中,Publisher与Book两个模型的定义及其与视图的交互方式,通过URL配置实现一对多关系的数据展示。具体介绍了如何在视图中使用ORM操作数据库,并在HTML页面上动态展示数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

models.py

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=200)
    city = models.CharField(max_length=50)
    country = models.CharField(max_length=30)
    website = models.URLField()


class Book(models.Model):
    title = models.CharField(max_length=50)
    publicate_date = models.DateField()
    publisher = models.ForeignKey(Publisher, null=True)

urls.py

urlpatterns = [
    url('^otm/(\d*)$', views.otm_views),
]

views.py

def otm_views(request, pid):
    publishers = Publishere.objects.all()
    books = Book.objects.all()
    if pid:
        pid = int(pid)
        if pid > 0:
            books = Book.objects.filter(publisher_id=pid)
    return render(request, 'otm.html', locals())

html/otm.html

<p>
    <select id="selPub">
        <option value="0">===请选择===</option>
        {% for pub in publishers %}
            <option value="{{pub.id}}"
                {% if pub.id == pid %}
                    selected
                {% endif %}
            >
                {{pub.name}}
            </option>
        {% endfor %}
    </select>
</p>
<div>
    <table border="1" width="300">
        <tr>
            <th>书名</th>
            <th>出版时间</th>
        </tr>
        {% for b in books %}
            <tr>
                <td>{{ b.title }}</td>
                <td>{{ b.publicate_date }}</td>
            </tr>
        {% endfor %}
    </table>
</div>

javascript/otm.html

<script src="/static/js/jquery-1.11.3.js></script>
<script>
    $(function(){
        $("#selPub").change(function(){
            location.href = "/otm/"+this.value;
        });
    });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值