【问题标题】:Get access to model without related_name [closed]访问没有相关名称的模型[关闭]
【发布时间】:2017-10-02 19:41:03
【问题描述】:

我有模型日历:

class Calendar(models.Model):
    name = models.CharField(_('Name'), max_length=50)
    active = models.BooleanField(default=True)

这是带有相关名称的模型:

class Base(models.Model):
    calendar = models.ForeignKey(Calendar, related_name='base')
    code = models.CharField(_('Code'), max_length=2, default='DE')
    default = models.BooleanField(default=False)

这没问题,因为我可以通过以下方式访问日历:

base_ids = self.calendar.base.values_list('id', flat=True)

但我有另一个没有相关名称的模型:

class Post(models.Model):
    calendar = models.ForeignKey(Calendar)
    pub_date = models.DateTimeField(blank=True, null=True)

我试过了:

post_id = self.calendar_set.themes.values_list('id', flat=True)

但它不起作用。

【问题讨论】:

  • 您是否有任何理由不添加相关名称?
  • 不清楚上面两个例子中self是什么型号。 themes 是什么?
  • self.calendar = 日历@Alasdair
  • 好的,但是第二个例子甚至没有使用self.calendar。第二个例子中的self是什么?

标签: python django foreign-keys django-queryset


【解决方案1】:

从不需要添加相关名称才能访问模型。 (您唯一需要添加一个是在发生冲突时。)这里的默认值为post_set,它工作正常。

【讨论】:

  • 谢谢@daniel-roseman
猜你喜欢
  • 2022-11-15
  • 2013-10-21
  • 2015-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-26
  • 2017-07-16
  • 2020-11-14
相关资源
最近更新 更多