0

I am building a very simple app that requests users to add the name of a city into a poll and then creates a frequency distribution of entered cities. My view for some reason is not retrieving City objects from the database by their name (primary key). Specifically, the first assignment after try: is not going through, according to my trace statements. Must be overlooking something really obvious as I'm a novice. Please advise.

models.py:

from django.db import models

class City(models.Model):
    name = models.CharField(max_length='20', primary_key=True)
    count = 0

views.py:

def save(request):
name = request.POST['city_name']
try:
    city = City.objects.get(pk=name)
    print 'city does exist'
    city.count += 1
except City.DoesNotExist:
    print 'city does not exist'
    city = City()
    city.name = name
    city.count += 1
city.save()
return render_to_response('thanks.html', {'city_name':name})
entrepaul
  • 927
  • 3
  • 12
  • 23

2 Answers2

1

You need to call city.save() after changing city.count

You will need to do this in the try block and except block.

Steve
  • 7,171
  • 2
  • 30
  • 52
  • No problem, we all do it from time-to-time :) Sometimes it just needs a fresh pair of eyes. – Steve Jan 18 '13 at 18:55
  • @entrepaul what should city.count be? The number of all cities so far? Then try City.objects.count() – XORcist Jan 18 '13 at 19:55
1

Your model should be

class City(models.Model):
    name = models.CharField(max_length='20', primary_key=True)
    count = models.IntegerField(default=0)

As a side note, (https://docs.djangoproject.com/en/1.4/ref/models/querysets/#get-or-create) may help clean things up a bit.

Edit:

Nathaniel
  • 666
  • 4
  • 15
  • I think every time you get a City object the count will always be 0 and isn't actually saved to the database. I've not tested it out, so I'm not completely sure. – Nathaniel Jan 18 '13 at 19:37
  • Ok I think you're right, so I've changed it to count = IntegerField(default=0), but now it does not recognize count as a database table even after I do syncdb... Do you know why this might be happening? – entrepaul Jan 18 '13 at 19:43
  • Running syncdb won't add to an existing schema. You can drop the City table or use [south](http://south.aeracode.org/) to manage schema migrations. Another solution would be to manually add the count column as an integer field in the database. – Nathaniel Jan 18 '13 at 19:46
  • How do I drop the City table into the db? – entrepaul Jan 18 '13 at 19:49
  • 1
    This [post](http://stackoverflow.com/questions/2286276/how-do-i-drop-a-table-from-sqlite3-in-django) points out you can run: python manage.py reset app_name – Nathaniel Jan 18 '13 at 19:51