django管理员缺少记录

时间:2013-07-12 13:03:41

标签: python django django-admin

我有company_images属于country_master,除非country_id为 0 。如果country_id为0,我假设它是“所有位置”。但是因为country_master中不存在0。它不会返回company_images列表中的那些条目的结果。我如何解决它。

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

1 个答案:

答案 0 :(得分:0)

一种解决方法是,将country字段设为可空(null=True, blank=True),如果为空,则假定为all个位置。在我看来,这将更清洁。

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

相关问题