【问题标题】:Django query content_type by name not content_type_idDjango 按名称查询 content_type 而不是 content_type_id
【发布时间】:2020-10-26 17:47:30
【问题描述】:

我需要计算从我的 Flags 模型到我的 Post 模型的一些关系。现在我不明白如何在我的查询中查询 Post 模型名称,我了解如何查询 content_type_id 而不是 content_type (作为字符串)。我有这样的想法:

Q(models.Q(('app_label', 'App'), ('model', 'Post')) 

但我不知道当时的语法是什么样子的,可以 smb.帮忙?

示例:

def post_list_most_bad_flags(request):
    p_counter_query = Flags.objects.filter(content_type_id=12) # --> Want to replace this with content_type instead if content_type_id
    counter = p_counter_query.count()
    print(counter)

提前致谢

【问题讨论】:

    标签: python sql django


    【解决方案1】:

    鉴于Flags 具有ForeignKey(或OneToOneFieldContentType 模型,您可以使用以下方式过滤:

    def post_list_most_bad_flags(request):
        p_counter_query = Flags.objects.filter(
            content_type__app_label='App',
            content_type__model='Post'
        )
        counter = p_counter_query.count()
        print(counter)

    【讨论】:

      猜你喜欢
      • 2018-10-23
      • 2021-01-24
      • 1970-01-01
      • 2019-11-15
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      相关资源
      最近更新 更多