如何在django admin中过滤外键字段设置的django查询?

时间:2012-07-26 04:05:57

标签: python django

我想知道如何过滤外键字段设置的django查询?

以下适用于没有外键的模型。 例如

codes = Code.objects.extra(where=['CHAR_LENGTH(code_key) = 10'])

但它在带有外键的模型中不起作用。 例如

codes_fk = CodeRegistry.objects.extra(where=['CHAR_LENGTH(code__code_key) = 10'])

我想在“CodeRegistry”管理员列表中仅显示长度为10个字符的代码。提前谢谢!

models.py

class Code(models.Model):
    id = models.AutoField(primary_key=True)
    code_key = models.CharField(max_length=20,unique=True)
    redemption_date = models.DateTimeField(null=True, blank=True)
    user = models.ForeignKey(User, blank=True, null=True)
    movie = models.ForeignKey(Movie, blank=True, null=True)

class CodeRegistry(models.Model):
    code = models.ForeignKey(Code, blank=False, null=False, unique=True)
    view_count = models.IntegerField(default=0)
    last_watch_date = models.DateTimeField(null=True, blank=True)
    ip = models.IPAddressField(null=False,blank=False)

admin.py

class CodeAdmin(admin.ModelAdmin):
    fields = ['code_key','redemption_date','user','movie']

    #
    list_display = ('code_key','redemption_date','user','movie')

    #
    search_fields = ('code_key','user__email','movie__title')

    def queryset(self, request):
        """
        Filter the objects displayed in the change_list to only
        display those for the currently signed in user.
        """
        codes = Code.objects.extra(where=['CHAR_LENGTH(code_key) = 10'])
        return codes


class CodeRegistryAdmin(admin.ModelAdmin):
    fields = ['code','view_count','last_watch_date','ip']

    list_display = ('code','view_count','last_watch_date','ip')

    #
    search_fields = ['code']

    def queryset(self, request):
        """
        Filter the objects displayed in the change_list to only
        display those for the currently signed in user.
        """
        codes_fk = CodeRegistry.objects.extra(where=['CHAR_LENGTH(code_key) = 10'])
        return codes_fk

1 个答案:

答案 0 :(得分:5)

CHAR_LENGTH(code__code_key)是SQL。它不知道code__前缀。

一种可能的解决方案是:

code_regs = CodeRegistry.objects.filter(
    code__in=Code.objects
                 .extra(where=['CHAR_LENGTH(code_key) = 10']))