2014-04-26 210 views
3

我確實有以下兩種模式。所以我想要獲得某個課程的所有模塊。正如你所看到的,我已經得到了這個特定的課程。所以我只需要從中獲取模塊。我讀the docs關於過濾ManyToManyField,但仍然無法使其工作。我知道這可能太簡單,但無法解決。Django,查詢集過濾器ManyToManyField

models.py

class Course(models.Model): 
    name = models.CharField(max_length=100) 
    modules = models.ManyToManyField('Module', blank=True) 

class Module(models.Model): 
    code = models.CharField(max_length=10, unique=True) 
    name = models.CharField(max_length=65) 
    year = models.IntegerField() 

view.py

def ajax_get_modules(request, course): 
    current_course = Course.objects.get(pk=course).pk 
    modules = Module.objects.filter(...........) 
    if request.is_ajax(): 
     data = serializers.serialize('json', modules) 
     return HttpResponse(data, content_type="application/javascript") 

回答

5

嘗試:

current_course = Course.objects.get(pk=course) 
modules = Module.objects.all().filter(course=current_course) 
0
#models.py 
class Telephone(models.Model): 
    status    = models.IntegerField(default=0) 
    number    = models.CharField(max_length=255, blank=True) 

class Profile(models.Model): 
    first_name   = models.CharField(max_length=255, blank=True) 
    last_name    = models.CharField(max_length=255, blank=True) 
    telephone    = models.ManyToManyField(Telephone, blank=True, null=True) 

#views.py 
def api(request): 
    profile = Profile.objects.get(pk=1) #just as an example 
    primary_telephone  = profile.telephone.all().filter(status=1) 

#I was looking for the primary telephone of my client, this was the way I have solved. 
0

你必須在球場上的模型相關領域這是一個對M2M模塊,所以這可以讓你直接訪問模塊列表涉及到一門課程。

一旦你的過程中簡單地獲取它的所有模塊,像這樣:

course = Course.objects.get(pk=course_id) 
course_modules = course.modules.all() 

我總是勸包裝/,查詢課程與一試,除了第一行 - 這是因爲模型管理的get方法如果找不到結果可能會拋出異常。

這是可以做到像這樣:

try: 
    course = Course.objects.get(pk=course_id) 
except Course.DoesNotExist: 
    pass # Handle this exception