My Models has a FK to translations and also a many 2 many to categories which also them are translated
With this code I concatenate the translation of the categories and allow the changelist to order them.
works only on mysql but you can adapt to your DB
SET SESSION is required by mysql.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #admin.py
class GroupConcat(Aggregate):
name = 'GroupConcat'
def add_to_query(self, query, alias, col, source, is_summary):
aggregate = SQLGroupConcat(col, is_summary=is_summary, **self.extra)
query.aggregates[alias] = aggregate
class SQLGroupConcat(SQLAggregate):
sql_function = 'GROUP_CONCAT'
def __init__(self, col, separator=',', **extra):
self.sql_template = "%%(function)s(%%(field)s SEPARATOR '%s')" % separator
super(SQLGroupConcat, self).__init__(col, source=models.DecimalField(), **extra)
class TranslatedModelAdmin(admin.ModelAdmin):
def queryset(self, request):
qs = super(TranslatedModelAdmin, self).queryset(request)
from django.db import connection
cursor = connection.cursor()
cursor.execute('SET SESSION group_concat_max_len=100000')
a=cursor.fetchall()
cursor.close()
new_qs = qs.filter(translation_set__lang="%s" % get_language(), category__translation_set__lang='%s' % get_language())\
.annotate(groupconcat=GroupConcat('category__translation_set__title'))
return new_qs
def groupconcat(self):
return self.groupconcat
groupconcat.admin_order_field='groupconcat'
groupconcat.short_description='Categorie'
#model.py define those function inside the Model that need this feature
def get_translated_field(self, field, lang=get_language()):
try:
value = self.translation_set\
.filter(lang=get_language())\
.get().__getattribute__(field)
return value
except ObjectDoesNotExist:
return (translation_error % field)
def get_translated_title(self):
return self.get_translated_field("title")
get_translated_title.allow_tags=True
get_translated_title.short_description="Title"
get_translated_title.admin_order_field="translation_set__title"
list_display = ( 'get_translated_title', groupconcat)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.