Commit 80209ed2 authored by Daniel Klaffenbach's avatar Daniel Klaffenbach 🐍

admin: Fix cast-errors on PostgreSQL

parent 7f20b9a0
Pipeline #8341 passed with stage
in 2 minutes and 9 seconds
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.db.models import Q, ForeignKey
from django.db.models import CharField, ForeignKey, Q
try:
from django.db.models.functions import Cast
except ImportError:
CAST_AVAILABLE = False
else:
CAST_AVAILABLE = True
from .models import JournalEntry
class JournalAdmin(admin.ModelAdmin):
......@@ -46,9 +52,22 @@ class JournalAdmin(admin.ModelAdmin):
break
if not fk_name:
continue
# JournalEntry.object_id is a CharField and some databases (e.g. PostgreSQL) are picky when values
# from IntegerFields are passed in. This is why we need to cast the objects' pk into a string. This
# can be done either by the database (preferred) or in Python (legacy Django version).
if CAST_AVAILABLE:
related_pks = model.objects.filter(
**{fk_name: object_id}
).annotate(
pk=Cast('id', CharField(max_length=255))
).values_list('pk', flat=True)
else:
# Do the cast in Python, which may be slower
related_pks = [str(i) for i in model.objects.filter(**{fk_name: object_id}).values_list('pk', flat=True)]
# Finds all JournalEntries for `inline.model`
inline_filter = Q(Q(object_id__in=model.objects.filter(**{fk_name: object_id}).values_list('pk', flat=True)) &
inline_filter = Q(Q(object_id__in=related_pks) &
Q(content_type__app_label=model._meta.app_label) &
Q(content_type__model=model.__name__.lower()))
journal_filter = journal_filter | inline_filter
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment