【问题标题】:django admin missing recordsdjango admin 缺少记录
【发布时间】: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


【解决方案1】:

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

另一种方法是为all 选项创建一个CountryMaster 对象(作为固定装置) - 换句话说,加载到数据库的固定装置,带有name=allCountryMaster 对象。因此,无论何时用户选择all,您都可以将引用分配给该对象。

【讨论】:

  • 我想知道如何在添加表单的下拉菜单中添加额外的条目。
猜你喜欢
  • 1970-01-01
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多