2012-02-07 42 views
0

我有以下結構在Django:Django-多對多現場查詢的型號

class BodySubPart(models.Model): 
    body_subpart=models.CharField(max_length=20) 
    def __str__(self): 
     return self.body_subpart 

class BodyPart(models.Model): 
    body_part=models.CharField(max_length=20) 
    body_subpart=models.ManyToManyField(BodySubPart) 
    def __str__(self): 
     return self.body_part 

例:

example, 
if BodyPart=head then BodySubPart= face,mouth,eyes,nose. 
if BodyPart=arm then BodySubPart= shoulder,fingers,elbow. 

很多這樣的身體部位被存儲。 ... 現在我想創建一個運行時窗體有兩個選擇域(BodySubPart和BodyPart),這樣當我選擇BodyPart時,它應該更改BodySubPart中的列表。例如,

The first choicefield has body parts={head,arm,chest...} 
The second choice field should change when i select a particular part 
If i select "head" then second choice field should show, 
body sub parts={face,mouth,eyes,nose...} 

請幫我在這裏.....

回答

1

你嘗試過什麼?我想你會發現,如果你真的自己嘗試過某些東西,而不是僅僅希望別人爲你做,就會更願意幫助你。它應該是這樣的:

1) BodyPart.objects.all() # all body parts 
2) head = BodyPart.objects.get(body_part='head') 
     head_subparts = head.body_subpart.all() # all head subparts 

Django的做了解釋如何查詢這些關係的一個偉大的工作。 https://docs.djangoproject.com/en/dev/topics/db/models/#many-to-many-relationships 此外,還有一些關於djangos的manytomany關係的在線教程。

1

這一點需要一些AJAX的,所以第一步是創建一個視圖來處理:

from django.core import serializers 
from django.http import HttpResponse, HttpResponseBadRequest 
from django.shortcuts import get_list_or_404 

def ajax_get_bodysubparts(request): 
    bodypart_id = request.GET.get('bodypart_id') 

    if bodypart_id: 
     bodysubparts = get_list_or_404(BodySubPart, bodypart__id=bodypart_id) 
     data = serializers.serialize('json', bodysubparts) 
     return HttpResponse(data, mimetype='application/json') 
    else: 
     return HttpResponseBadRequest() 

領帶在urls.py.一些網址於是,一些JavaScript爲表單(假定的jQuery):

$(document).ready(function(){ 
    $('#id_bodypart').change(function(){ 
     var selected = $(this).val(); 
     if (selected) { 
      $.getJSON('/url/to/ajax/view/', { 
       'bodypart_id': selected 
      }, function (data, jqXHR) { 
       options = []; 
       for (var i=0; i<data.length; i++) { 
        options.append('<option value="'+data[i].id+'">'+data[i].body_subpart+'</option>'); 
       } 
       $('#id_bodysubpart).html(options.join('')); 
      }); 
     } 
    }); 
}); 
0

你可能會需要自定義表單字段和部件的組合來得到你想要的。

檢查出django-ajax-filtered-fields項目,看看它是否接近你正在尋找的東西。它至少會提供一些指導,如果你決定創建自己的。

您將需要一些JavaScript來創建一個新請求來動態填充您的字段,以便標準django表單也不可用。