2

I'm working a simple search result page in Django.

The user searches by text and adds a city field from a dropdown.

The query is as follows:

if 'query' in request.GET and request.GET['query']:
    city = request.GET['city']
    q = request.GET['query']
    ct = Classified.objects.filter(name__icontains=q).filter(city__exact=city)
    return render(request, 'template/search.html', {'ct': ct, 'query': q})

The model for Classified is as follows:

class Classified(models.Model):
    name = models.CharField(max_length=256, unique=True)
    email = models.CharField(max_length=100)
    category = models.ForeignKey(Categories)
    phone_number = models.IntegerField(max_length=10, default=0)
    address = models.CharField(max_length=1000)
    id = models.IntegerField(primary_key=True)
    city = models.ForeignKey(Cities)
    image = models.ImageField(blank=True, upload_to='static/img/')

    def __unicode__(self):
        return self.name

Cities is as follows:

class Cities(models.Model):
    name = models.CharField(max_length=256)

    def __unicode__(self):
        return self.name

On search, the /search/ page gives me the following error:

invalid literal for int() with base 10: 'Searched-city'

What am I missing out on?

Newtt
  • 6,050
  • 13
  • 68
  • 106
  • 1
    Do you have a complete traceback? – Wooble Apr 30 '14 at 17:35
  • There are plenty of questions in the related questions list that appear to be pretty similar. Di you take a look? – devnull Apr 30 '14 at 17:35
  • @devnull, yeah I did look at these two: http://stackoverflow.com/questions/13861594/python-3-3-programming-valueerror-invalid-literal-for-int-with-base-10-be and this http://stackoverflow.com/questions/1841565/valueerror-invalid-literal-for-int-with-base-10. Didn't help much. – Newtt Apr 30 '14 at 17:37

1 Answers1

5

City is a foreign key, you need to update your query to proxy through the relationship by explicitly saying city__name__exact

ct = Classified.objects.filter(name__icontains=q).filter(city__name__exact=city)
Bryan
  • 6,682
  • 2
  • 17
  • 21
  • What caused the original error with casting to an `int`, though? (For my own edification.) – 2rs2ts Apr 30 '14 at 17:38
  • 1
    Because it's attempting to cast the string value of city, to the literal foreign key (primary key on the cities table). City__exact is referring to the primary key, not a subfield of that table – Bryan Apr 30 '14 at 17:39
  • And the primary key is...? I should know this, but is it a uid Django generates? – 2rs2ts Apr 30 '14 at 17:53
  • 2
    https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields – Bryan Apr 30 '14 at 23:25
  • 1
    Perfect, that's what I thought I remembered (and it elucidates your answer as well!) – 2rs2ts May 01 '14 at 13:09