0

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

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

1 回答 1

0

一种解决方法是,使country字段可为空 ( null=True, blank=True),如果为空,则假定all位置。那,在我看来会更干净。

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.

于 2013-07-12T13:45:22.070 回答