user1163236
user1163236

Reputation: 223

Django- Many to Many field querying

I have following structure of models in 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

Ex:

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

like this many body parts are stored. ... now I want to create a runtime form have two choicefields (BodySubPart and BodyPart) such that when i select the BodyPart it should change the list in BodySubPart. Ex.

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...}

Please help me here.....

Upvotes: 0

Views: 876

Answers (3)

Kekoa
Kekoa

Reputation: 28240

You will probably need a combination of custom form fields and widgets to get what you want.

Check out the django-ajax-filtered-fields project to see if that is close what you are looking for. It will at least provide some guidance if you decide to create your own.

You will need some javascript to make a new request to populate your fields dynamically, so that will also not be available with standard django forms.

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239250

This requires a bit of AJAX, so first step is to create a view to handle that:

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()

Tie that to some URL in urls.py. Then, some JavaScript for your form (assumes 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(''));
            });
        }
    });
});

Upvotes: 1

dm03514
dm03514

Reputation: 55952

What have you tried?? I think you will find people are more willing to help you if you have actually tried something yourself and not just want others to do it for you. It should go something like this:

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 does a great job of explaining how to query these relationships. https://docs.djangoproject.com/en/dev/topics/db/models/#many-to-many-relationships In addition there are a number of really great tutorials online regarding djangos' manytomany relationships.

Upvotes: 1

Related Questions