Hafiz
Hafiz

Reputation: 4267

simple reverse in query in django

I am trying to get country where some specific post exists, so that I can show only those countries. To do so. I have following code.

Models:

class Country(models.Model):
    name=models.CharField(max_length=100)
    iso_code_2=models.CharField(max_length=4)
    iso_code_3=models.CharField(max_length=4)
    def __unicode__(self):
        return self.name
    def get_countries_with_jobs(self):
        countries=self.objects.filter(id__in=Post.country)
        return countries


class Category(models.Model):
    name=models.CharField(max_length=100)
    title=models.CharField(max_length=100)
    meta_keywords=models.CharField(max_length=100)
    meta_description=models.CharField(max_length=100)
    sort_order=models.IntegerField()
    def __unicode__(self):
        return self.name

class City(models.Model):
    name=models.CharField(max_length=100)
    title=models.CharField(max_length=100)
    meta_keywords=models.CharField(max_length=100)
    meta_description=models.CharField(max_length=100)
    sort_order=models.IntegerField()
    country=models.ForeignKey(Country)
    def __unicode__(self):
        return self.title

class Post(models.Model):
    user=models.ForeignKey(User)
    title=models.CharField(max_length=100)
    publish_date=models.DateField()
    active=models.BooleanField()
    country=models.ForeignKey(Country)
    city=ChainedForeignKey(City,chained_field="country",chained_model_field="country" )
    category=models.ForeignKey(Category)
    description=models.TextField()
    added_by=models.CharField(max_length=70)
    def __unicode__(self):
        return self.title

Here get_countries_with_jobs method have the code that is trying to query and get countries where post exist. Normally one access country of some post, but in this case I need to get countries where post exists. Here it was giving error while calling this method so I tried to write this code in view method as below.

def list(request,template_name='list_posts.html'):
     countries=Country.objects.filter(id__in=Posts.country)
     return render_to_response(template_name,locals(),context_instance=RequestContext(request))

Upvotes: 0

Views: 83

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239380

Your question is hard to understand, so I'll look at a couple of interpretations:

  1. You want to get countries for a particular post:

    countries = Country.objects.filter(post=post_instance)
    
  2. You want to get all countries that have any posts:

    countries = Country.objects.filter(post__isnull=False)
    

    Similarly, if you wanted to get countries that don't have a post associated with them:

    countries = Country.objects.filter(post__isnull=True)
    

Upvotes: 1

Related Questions