zoukankan      html  css  js  c++  java
  • django模型多对多调用

     

    对于如下的模型:

    from django.db import models
    
    # Create your models here.
    
    class Student(models.Model):
        name = models.CharField(max_length=128)
    
    class Course(models.Model):
        name = models.CharField(max_length=128)
        students = models.ManyToManyField('Student')
    

    模型Course有一个多对多字段指向Student模型。

    正向查询

    假设编写了一个如下的视图:

    def test(request):
        course = models.Course.objects.get(pk=1)
        return render(request, 'course.html', locals())
    

    获取了id为1的course对象,并将它传递给course.html模版,模版代码如下:

    {% for student in course.students.all %}
    
    <p>{{ student.name }}</p>
    
    {% endfor %}
    

    首先通过course.students.all,查寻到course对象关联的students对象集,然后用for标签循环它,获取每个student对象,再用student模型的定义,访问其各个字段的属性。

    反向查询

    对于反向查询,从student往course查,假设有如下的视图:

    def test2(request):
        student = models.Student.objects.get(pk=1)
        return render(request, 'student.html', locals())
    

    获取了id为1的student对象,并将它传递给student.html模版,模版代码如下:

    {% for course in  student.course_set.all %}
    {{ course.name }}
    {% endfor %}

    通过student.course_set.all,反向获取到student实例对应的所有course对象,然后再for标签循环每个course,调用course的各种字段属性。

    对于外键ForeignKey,其用法基本类似。只不过正向是obj.fk,且只有1个对像,不是集合。反向则是obj.fk_set,类似多对多。

  • 相关阅读:
    nyoj 95 众数问题(set)
    nyoj 93 汉诺塔(三)(stack)
    hdu 1010 Tempter of the Bone
    nyoj 55 懒省事的小明(priority_queue优先队列)
    nyoj 31 5个数求最值
    poj 1256 Anagram
    next_permutation函数
    nyoj 19 擅长排列的小明(深搜,next_permutation)
    nyoj 8 一种排序(用vector,sort,不用set)
    nyoj 5 Binary String Matching(string)
  • 原文地址:https://www.cnblogs.com/cheyunhua/p/11052339.html
Copyright © 2011-2022 走看看