Newtt
Newtt

Reputation: 6190

Iterating through form data

I have a QueryDict object in Django as follows:

{'ratingname': ['Beginner', 'Professional'], 'sportname': ['2', '3']

where the mapping is such:

2 Beginner
3 Professional

and 2, 3 are the primary key values of the sport table in models.py:

class Sport(models.Model):
    name = models.CharField(unique=True, max_length=255)

class SomeTable(models.Model):
    sport = models.ForeignKey(Sport)
    rating = models.CharField(max_length=255, null=True)

My question here is, how do I iterate through ratingname such that I can save it as

st = SomeTable(sport=sportValue, rating=ratingValue)
st.save()

I have tried the following:

ratings = dict['ratingname']
sports = dict['sportname']
for s,i in enumerate(sports):
    sport = Sport.objects.get(pk=sports[int(s[1])])
    rate = SomeTable(sport=sport, rating=ratings[int(s)])
    rate.save()

However, this creates a wrong entry in the tables. For example, with the above given values it creates the following object in my table:

id: 1
sport: 2
rating: 'g'

How do I solve this issue or is there a better way to do something?

Upvotes: 0

Views: 66

Answers (2)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

There are a couple of problems here. The main one is that QueryDicts return only the last value when accessed with ['sportname'] or the like. To get the list of values, use getlist('sportname'), as documented here: https://docs.djangoproject.com/en/1.7/ref/request-response/#django.http.QueryDict.getlist

Your enumerate is off, too - enumerate yields the index first, which your code assigns to s. So s[1] will throw an exception. There's a better way to iterate through two sequences in step, though - zip.

ratings = query_dict.getlist('ratingname') # don't reuse built in names like dict
sports = query_dict.getlist('sportname')
for rating, sport_pk in zip(ratings, sports):
    sport = Sport.objects.get(pk=int(sport_pk))
    rate = SomeTable(sport=sport, rating=rating)
    rate.save()

You could also look into using a ModelForm based on your SomeTable model.

Upvotes: 1

satoru
satoru

Reputation: 33215

You may use zip:

ratings = dict['ratingname']
sports = dict['sportname']
for rating, sport_id in zip(ratings, sports):
    sport = Sport.objects.get(pk=int(sport_id))
    rate = SomeTable(sport=sport, rating=rating)
    rate.save()

Upvotes: 1

Related Questions