Many 2 Many Admin Ordering with 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

  1. Advanced Search in django admin by visik7 3 years, 3 months ago
  2. django-mptt enabled FilteredSelectMultiple m2m widget by anentropic 4 years, 5 months ago
  3. dumpdata/loaddata with MySQL and ForeignKeys (Revision 2) by cmgreen 6 years ago
  4. dumpdata/loaddata with MySQL and ForeignKeys, as django command by brondsem 4 years, 12 months ago
  5. Ordering Models in Django Site administration screen by btbytes 6 years, 8 months ago

Comments

(Forgotten your password?)