tags:

views:

59

answers:

2

I am writing queryset in django. In the first queryset it is working fine. In the second it is giving the error " cannot resolve xyz into a field .. .. "

In models.py

class XYZ(models.Model):

  id= models.AutoField(primary_key=True)

  name = models.CharField(max_length=200)

  addres= models.CharField(max_length=200)

  def __unicode__():
    return self.name

class ASD(models.Model):
  id= models.AutoField(primary_key=True)
  pub = models.ForeignKey(XYZ)
  city= models,CHarField(max_length=200)

First queryset:

queryset= XYZ.objects.filter(asd__pub____exact='4535344sds3646fhgf7987')

Second queryset:

queryset= ASD.objects.filter(xyz__id____exact='4535344sds3646fhgf7987')

But acccording to django docs it should work.

A: 

The error is telling you that the ASD objects in your QuerySet don't have an xyz field. Is it possible that you've got a typo or the Field name isn't just the lowercase version of the name of the Model it is referencing?

Hank Gay
A: 

In the docs you reference, look closely at the Entry Model:

class Entry(models.Model):
    blog = models.ForeignKey(Blog)

and how it references the Blog Model:

>>> Entry.objects.filter(blog__name__exact='Beatles Blog')

blog was defined as a field that is a ForeignKey to a Blog Model. It is not getting fancy and resolving the foreign model name ("Blog" in this case) to a field value ("blog"); it is simply using the name that you give it. Therefore, you should change your ASD model definition:

class ASD(models.Model):
  xyz = models.ForeignKey(XYZ)

You have pub now, but you are trying to retrieve it by using xyz, which is undefined. Also, you have too many underscores in one place; it should read:

queryset= ASD.objects.filter(xyz__id__exact='4535344sds3646fhgf7987')

Of course, you could change the one query to:

queryset= ASD.objects.filter(pub__id__exact='4535344sds3646fhgf7987')
geowa4