2013-07-12 52 views
0

我有属于country_master除非COUNTRY_ID是一个company_images表。如果country_id是0,我假设它是'全部位置'。但是因为country_master中不存在0。它对于company_images列表中的条目没有返回结果。我如何解决它。Django管理缺失的记录

原谅我,如果这是一件简单的事情因为我是新的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" 

我已经试过这一点,并在admin.py提到这一点,作为显示提起

def country_name(self): 
    if self.country_id is 0: 
     return "ALL" 
    else: 
     return self.country 
country_name.short_description = 'Country' 
+0

解决办法之一是,使'country'为空('null = True,空白= True'),如果空白,则假定__all__位置。这在我看来会更清洁。另一种选择,有一个特殊的价值 - country_master.name ='all'',并将__all__个案分配给该对象 – karthikr

+0

这对我有用。 plz把这个作为答案。以便我可以将其标记为正确的答案。 – aWebDeveloper

+0

也可以解释选项b的细节。我没有得到它 – aWebDeveloper

回答

0

一个解决办法是,让country场可为空(null=True, blank=True),如果空,假设all位置。这在我看来会更清洁。

另一种方法是创建一个对象CountryMaster(作为夹具)为all选项 - 换句话说,加载到数据库的夹具,CountryMaster对象与name=all。因此,只要用户选择all,就可以为该对象分配引用。

+0

我想知道如何添加额外的条目下拉式添加表单。 – aWebDeveloper

+0

[看这里](http://stackoverflow.com/questions/3700445/add-additional-options-to-django-form-select-widget) – karthikr