0

I have a company_images table that belongs to country_master except when country_id is 0. If country_id is 0 i am assuming it's 'all locations'. But since 0 doesn't exist in country_master. It returns no result for those entry in company_images listing. How do i fix it.

Forgive me if this is a simple thing coz i am new to python/django.

Model.py

class CountryMaster(models.Model):
    country_id = models.IntegerField(primary_key=True)
    country_name = models.CharField(max_length=255)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "country_master"

    def __unicode__(self):
        if self.country_name is None:
            return "None"
        else:
            return self.country_name


class CompanyImage(models.Model):
    image_url = models.ImageField(upload_to='company', max_length=255)
    country = models.ForeignKey(CountryMaster)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)

class Meta:
    db_table = "company_images"

def __unicode__(self):
    return "None"

I have tried this and mentioning this in admin.py as a display filed

def country_name(self):
    if self.country_id is 0:
        return "ALL"
    else:
        return self.country
country_name.short_description = 'Country' 
aWebDeveloper
  • 36,687
  • 39
  • 170
  • 242
  • One work around is, make `country` nullable (`null=True, blank=True`) and if blank, assume __all__ locations. That, in my opinion would be cleaner. Another option, Have a special value - `country_master.name='all'`, and assign the __all__ case to that object – karthikr Jul 12 '13 at 13:39
  • this works for me. plz put this up as the answer. so that i can mark it as the correct answer. – aWebDeveloper Jul 12 '13 at 13:43
  • also could you explain option b in details. i didn't get it – aWebDeveloper Jul 12 '13 at 13:44

1 Answers1

0

One work around is, make country field nullable (null=True, blank=True) and if empty, assume all locations. That, in my opinion would be cleaner.

Another approach would be to create a CountryMaster object (as a fixture) for the all option - In other words, a fixture that loads to the database, a CountryMaster object with name=all. So, whenever the user selects all, you can assign the reference to this object.

karthikr
  • 97,368
  • 26
  • 197
  • 188