【发布时间】:2013-07-12 13:03:41
【问题描述】:
我有一个company_images 表属于 到country_master,但 country_id 为 0 时除外。如果 country_id 为 0,我假设它是“所有位置”。但由于 country_master 中不存在 0。它不会为 company_images 列表中的那些条目返回任何结果。我如何解决它。
如果这是一件简单的事情,请原谅我,因为我是 python/django 的新手。
模型.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'
【问题讨论】:
-
一种解决方法是,将
country设为可空 (null=True, blank=True),如果为空,则假定为 所有 个位置。那,在我看来会更干净。另一种选择,具有特殊值 -country_master.name='all',并将 all 大小写分配给该对象 -
这对我有用。请把这个作为答案。这样我就可以将其标记为正确答案。
-
您能否详细解释一下选项 b。我没听懂
标签: python django django-admin