外部キーフィールドによって設定された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