简体   繁体   中英

How to filter a django query set by a foreign key field, in django admin?

I would like to know how to filter a django query set by a foreign key field?

The following works in a model with no foreign key. Eg.

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

But it doesn't work in a model with foreign key. Eg.

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

I want to display only codes with a length of 10 characters in 'CodeRegistry' Admin list. Thanks in advance!

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

CHAR_LENGTH(code__code_key) is SQL. It doesn't know about the code__ prefix.

One possible solution is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM