SpeedyH30 February 2016

Only pulling one item out of a django manytomany

This should pull one record out of the model shown at the bottom to pass to javascript to display on the UI. I'm having issues pulling the location manytomany data to push across. this is because it only pulls one item and not all the items associated in the many to many. location is used to place the tags on a select2 multiselect the skillset data is not required currently

def GetPersonnelData(request, res_id):

    data = []

    res = Resource.objects.get(id=res_id)
    if not res: return HttpResponseNotFound()

    role = list(Role.objects.values_list('role_name').filter(id=res.role_id))
    emp = list(Employer.objects.values_list('employer_name').filter(id=res.employer_id))
    teamz = list(Team.objects.values_list('team_name').filter(id=res.teams_id))

    t = {
            "title":res.title,
            "pk":res.pk,
            "last_name":res.last_name,
            "preferred_name":res.preferred_name,
            "employstatus":res.employstatus,
            "employer":emp,
            "business_phone":res.business_phone, 
            "mobile_phone":res.mobile_phone,
            "email":res.email,
            "teams":teamz,
            "role_name":role,
            "notes":res.notes,
            "updated_by":res.updated_by,
            "updated_on":res.updated_on,
        }

    data.append(t);
    print data

    loc = Resource.objects.get(pk=res_id)
    for x in loc.location.all().filter(resource=res_id):
        l = {
            "location":x.name,
            }
    print x

Django Model

class Resource(models.Model):
    title = models.CharField(max_length=10)
    preferred_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=30)
    employer = models.ForeignKey('Employer')
    employstatus = models.CharField(max_length=20)
    role = models.ForeignKey('Role')
    teams = models.ForeignKey('Team')
    locat        

Answers


Rolf February 2016

If you want print x to print all the locations you should change the indentation to be within the for block (it's outside it now, you should be getting a unknown name error). Like so:

for x in loc.location.all().filter(resource=res_id):
    l = {
        "location":x.name,
        }
    print x

If you want to gather all the location names into the dict l you should change it to this:

l = {"location":[]}
for x in loc.location.all().filter(resource=res_id):
    l["location"] += x.name

Before you were creating a new dict on every iteration of the loop only keeping the result of the last instantiation.

Post Status

Asked in February 2016
Viewed 2,071 times
Voted 8
Answered 1 times

Search




Leave an answer