【问题标题】:How to access raw ForeignKey value directly in Django ORM and use it in search_fields?如何在 Django ORM 中直接访问原始 ForeignKey 值并在 search_fields 中使用它?
【发布时间】:2018-08-17 20:16:08
【问题描述】:

假设我有这些模型:

class First(models.Model):
    id = models.SlugField(primary_key=True)

class Second(models.Model):
    foo = models.ForeignKey('First')

这在技术上意味着Second.foo 是一个SlugField,它指向First 模型的主键。

问题是如何在不引用和使用First 模型的情况下访问foo 中的原始值?

额外问题:如何在不指向子模型字段的情况下使该字段在 Django 管理面板中可搜索?

那么如何做这样的事情呢?

@admin.register(Second)
class SecondAdmin(admin.ModelAdmin):
    search_fields = ['foo_id',]

不是这个?

@admin.register(Second)
class SecondAdmin(admin.ModelAdmin):
    search_fields = ['foo__id',]

【问题讨论】:

    标签: python django django-models django-admin django-queryset


    【解决方案1】:

    主要问题的答案是在被引用的变量末尾添加 _id:

    Second.objects.filter(foo_id='something')
    

    【讨论】:

      猜你喜欢
      • 2012-01-22
      • 2012-06-28
      • 2011-08-11
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多