Source

django-cms-mycmsproject-toporojo / hvad / manager.py

Full commit
  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
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
from collections import defaultdict
from django.conf import settings
from django.db import models, transaction, IntegrityError
from django.db.models.query import (QuerySet, ValuesQuerySet, DateQuerySet, 
    CHUNK_SIZE)
from django.db.models.query_utils import Q
from django.utils.translation import get_language
from hvad.fieldtranslator import translate
from hvad.utils import combine
import django
import logging
import sys

logger = logging.getLogger(__name__)

# maybe there should be an extra settings for this
FALLBACK_LANGUAGES = [ code for code, name in settings.LANGUAGES ]

class FieldTranslator(dict):
    """
    Translates *shared* field names from '<shared_field>' to
    'master__<shared_field>' and caches those names.
    """
    def __init__(self, manager):
        self.manager = manager
        self.shared_fields = tuple(self.manager.shared_model._meta.get_all_field_names()) + ('pk',)
        self.translated_fields  = tuple(self.manager.model._meta.get_all_field_names())
        super(FieldTranslator, self).__init__()
        
    def get(self, key):
        if not key in self:
            self[key] = self.build(key)
        return self[key]
    
    def build(self, key):
        """
        Checks if the selected field is a shared field
        and in that case, prefixes it with master___
        It also handles - and ? in case its called by
        order_by()
        """
        if key == "?":
            return key
        if key.startswith("-"):
            prefix = "-"
            key = key[1:]
        else:
            prefix = ""
        if key.startswith(self.shared_fields):
            return '%smaster__%s' % (prefix, key)
        else:
            return '%s%s' % (prefix, key)


class ValuesMixin(object):
    def _strip_master(self, key):
        if key.startswith('master__'):
            return key[8:]
        return key
       
    def iterator(self):
        for row in super(ValuesMixin, self).iterator():
            if isinstance(row, dict):
                yield dict([(self._strip_master(k), v) for k,v in row.items()])
            else:
                yield row


class DatesMixin(object):
    pass


#===============================================================================
# Default 
#===============================================================================

        
class TranslationQueryset(QuerySet):
    """
    This is where things happen.
    
    To fully understand this project, you have to understand this class.
    
    Go through each method individually, maybe start with 'get', 'create' and
    'iterator'.
    
    IMPORTANT: the `model` attribute on this class is the *translated* Model,
    despite this being used as the queryset for the *shared* Model!
    """
    override_classes = {
        ValuesQuerySet: ValuesMixin,
        DateQuerySet: DatesMixin,
    }
    
    def __init__(self, model=None, query=None, using=None, real=None):
        self._local_field_names = None
        self._field_translator = None
        self._real_manager = real
        self._fallback_manager = None
        self._language_code = None
        super(TranslationQueryset, self).__init__(model=model, query=query, using=using)

    #===========================================================================
    # Helpers and properties (INTERNAL!)
    #===========================================================================

    @property
    def shared_model(self):
        """
        Get the shared model class
        """
        return self._real_manager.model
        
    @property
    def field_translator(self):
        """
        Field translator for this manager
        """
        if self._field_translator is None:
            self._field_translator = FieldTranslator(self)
        return self._field_translator
        
    @property
    def shared_local_field_names(self):
        if self._local_field_names is None:
            self._local_field_names = self.shared_model._meta.get_all_field_names()
        return self._local_field_names
    
    def _translate_args_kwargs(self, *args, **kwargs):
        # Translated kwargs from '<shared_field>' to 'master__<shared_field>'
        # where necessary.
        newkwargs = {}
        for key, value in kwargs.items():
            newkwargs[self.field_translator.get(key)] = value
        # Translate args (Q objects) from '<shared_field>' to
        # 'master__<shared_field>' where necessary.
        newargs = []
        for q in args:
            newargs.append(self._recurse_q(q))
        return newargs, newkwargs
    
    def _translate_fieldnames(self, fieldnames):
        newnames = []
        for name in fieldnames:
            newnames.append(self.field_translator.get(name))
        return newnames

    def _reverse_translate_fieldnames_dict(self, fieldname_dict):
        """
        Helper function to make sure the user doesnt get "bothered"
        with the construction of shared/translated model

        Translates e.g.
        {'master__number_avg': 10} to {'number__avg': 10}

        """
        newdict = {}
        for key, value in fieldname_dict.items():
            if key.startswith("master__"):
                key = key.replace("master__", "")
            newdict[key] = value
        return newdict

    def _recurse_q(self, q):
        """
        Recursively translate fieldnames in a Q object.
        
        TODO: What happens if we span multiple relations?
        """
        newchildren =  []
        for child in q.children:
            if isinstance(child, Q):
                newq = self._recurse_q(child)
                newchildren.append(self._recurse_q(newq))
            else:
                key, value = child
                newchildren.append((self.field_translator.get(key), value))
        q.children = newchildren
        return q
    
    def _find_language_code(self, q):
        """
        Checks if it finds a language code in a Q object (and it's children).
        """
        language_code = None
        for child in q.children:
            if isinstance(child, Q):
                language_code = self._find_language_code(child)
            elif isinstance(child, tuple):
                key, value = child
                if key == 'language_code':
                    language_code = value
            if language_code:
                break
        return language_code
    
    def _split_kwargs(self, **kwargs):
        """
        Split kwargs into shared and translated fields
        """
        shared = {}
        translated = {}
        for key, value in kwargs.items():
            if key in self.shared_local_field_names:
                shared[key] = value
            else:
                translated[key] = value
        return shared, translated
    
    def _get_class(self, klass):
        for key, value in self.override_classes.items():
            if issubclass(klass, key):
                return type(value.__name__, (value, klass, TranslationQueryset,), {})
        return klass
    
    def _get_shared_query_set(self):
        qs = super(TranslationQueryset, self)._clone()
        qs.__class__ = QuerySet
        # un-select-related the 'master' relation
        del qs.query.select_related['master']
        accessor = self.shared_model._meta.translations_accessor
        # update using the real manager
        return self._real_manager.filter(**{'%s__in' % accessor:qs})
    
    #===========================================================================
    # Queryset/Manager API 
    #===========================================================================
    
    def language(self, language_code=None):
        if not language_code:
            language_code = get_language()
        self._language_code = language_code
        return self.filter(language_code=language_code)
    
    def __getitem__(self, k):
        """
        Handle getitem special since self.iterator is called *after* the
        slicing happens, when it's no longer possible to filter a queryest.
        Therefore the check for _language_code must be done here.
        """
        if not self._language_code:
            return self.language().__getitem__(k)
        return super(TranslationQueryset, self).__getitem__(k)
        
    def create(self, **kwargs):
        if 'language_code' not in kwargs:
            if self._language_code:
                kwargs['language_code'] = self._language_code
            else:
                kwargs['language_code'] = get_language()
        obj = self.shared_model(**kwargs)
        self._for_write = True
        obj.save(force_insert=True, using=self.db)
        return obj
    
    def get(self, *args, **kwargs):
        """
        Get an object by querying the translations model and returning a 
        combined instance.
        """
        # Enforce a language_code to be used
        newargs, newkwargs = self._translate_args_kwargs(*args, **kwargs)
        # Enforce 'select related' onto 'master'
        # Get the translated instance
        found = False
        qs = self
        
        
        if 'language_code' in newkwargs:
            language_code = newkwargs.pop('language_code')
            qs = self.language(language_code)
            found = True
        elif args:
            language_code = None
            for arg in args:
                if not isinstance(arg, Q):
                    continue
                language_code = self._find_language_code(arg)
                if language_code:
                    break
            if language_code:
                qs = self.language(language_code)
                found = True
        else:
            for where in qs.query.where.children:
                if where.children:
                    for child in where.children:
                        if child[0].field.name == 'language_code':
                            found = True
                            break
                if found:
                    break
        if not found:
            qs = self.language()
        # self.iterator already combines! Isn't that nice?
        return QuerySet.get(qs, *newargs, **newkwargs)

    def get_or_create(self, **kwargs):
        """
        Looks up an object with the given kwargs, creating one if necessary.
        Returns a tuple of (object, created), where created is a boolean
        specifying whether an object was created.
        """
        assert kwargs, \
                'get_or_create() must be passed at least one keyword argument'
        defaults = kwargs.pop('defaults', {})
        lookup = kwargs.copy()
        for f in self.model._meta.fields:
            if f.attname in lookup:
                lookup[f.name] = lookup.pop(f.attname)
        try:
            self._for_write = True
            return self.get(**lookup), False
        except self.model.DoesNotExist:
            try:
                params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
                params.update(defaults)
                # START PATCH
                if 'language_code' not in params:
                    if self._language_code:
                        params['language_code'] = self._language_code
                    else:
                        params['language_code'] = get_language()
                obj = self.shared_model(**params)
                # END PATCH
                sid = transaction.savepoint(using=self.db)
                obj.save(force_insert=True, using=self.db)
                transaction.savepoint_commit(sid, using=self.db)
                return obj, True
            except IntegrityError, e:
                transaction.savepoint_rollback(sid, using=self.db)
                exc_info = sys.exc_info()
                try:
                    return self.get(**lookup), False
                except self.model.DoesNotExist:
                    # Re-raise the IntegrityError with its original traceback.
                    raise exc_info[1], None, exc_info[2]

    def filter(self, *args, **kwargs):
        newargs, newkwargs = self._translate_args_kwargs(*args, **kwargs)
        return super(TranslationQueryset, self).filter(*newargs, **newkwargs)

    def aggregate(self, *args, **kwargs):
        """
        Loops over all the passed aggregates and translates the fieldnames
        """
        newargs, newkwargs = [], {}
        for arg in args:
            arg.lookup = self._translate_fieldnames([arg.lookup])[0]
            newargs.append(arg)
        for key in kwargs:
            value = kwargs[key]
            value.lookup = self._translate_fieldnames([value.lookup])[0]
            newkwargs[key] = value
        response = super(TranslationQueryset, self).aggregate(*newargs, **newkwargs)
        return self._reverse_translate_fieldnames_dict(response)

    def latest(self, field_name=None):
        if field_name:
            field_name = self.field_translator.get(field_name)
        return super(TranslationQueryset, self).latest(field_name)

    def in_bulk(self, id_list):
        raise NotImplementedError()

    def delete(self):
        qs = self._get_shared_query_set()
        qs.delete()
    delete.alters_data = True
    
    def delete_translations(self):
        self.update(master=None)
        super(TranslationQueryset, self).delete()
    delete_translations.alters_data = True
        
    def update(self, **kwargs):
        shared, translated = self._split_kwargs(**kwargs)
        count = 0
        if translated:
            count += super(TranslationQueryset, self).update(**translated)
        if shared:
            shared_qs = self._get_shared_query_set()
            count += shared_qs.update(**shared)
        return count
    update.alters_data = True

    def values(self, *fields):
        fields = self._translate_fieldnames(fields)
        return super(TranslationQueryset, self).values(*fields)

    def values_list(self, *fields, **kwargs):
        fields = self._translate_fieldnames(fields)
        return super(TranslationQueryset, self).values_list(*fields, **kwargs)

    def dates(self, field_name, kind=None, order='ASC'):
        field_name = self.field_translator.get(field_name)
        if int(django.get_version().split('.')[1][0]) <= 2:
            from nani.compat.date import DateQuerySet
            return self._clone(klass=DateQuerySet, setup=True,
                _field_name=field_name, _kind=kind, _order=order)
        return super(TranslationQueryset, self).dates(field_name, kind=kind, order=order)

    def exclude(self, *args, **kwargs):
        newargs, newkwargs = self._translate_args_kwargs(*args, **kwargs)
        return super(TranslationQueryset, self).exclude(*newargs, **newkwargs)

    def complex_filter(self, filter_obj):
        # Don't know how to handle Q object yet, but it is probably doable...
        # An unknown type object that supports 'add_to_query' is a different story :)
        if isinstance(filter_obj, models.Q) or hasattr(filter_obj, 'add_to_query'):
            raise NotImplementedError()
        
        newargs, newkwargs = self._translate_args_kwargs(**filter_obj)
        return super(TranslationQueryset, self)._filter_or_exclude(None, *newargs, **newkwargs)

    def annotate(self, *args, **kwargs):
        raise NotImplementedError()

    def order_by(self, *field_names):
        """
        Returns a new QuerySet instance with the ordering changed.
        """
        fieldnames = self._translate_fieldnames(field_names)
        return super(TranslationQueryset, self).order_by(*fieldnames)
    
    def reverse(self):
        return super(TranslationQueryset, self).reverse()

    def defer(self, *fields):
        raise NotImplementedError()

    def only(self, *fields):
        raise NotImplementedError()
    
    def _clone(self, klass=None, setup=False, **kwargs):
        kwargs.update({
            '_local_field_names': self._local_field_names,
            '_field_translator': self._field_translator,
            '_language_code': self._language_code,
            '_real_manager': self._real_manager,
            '_fallback_manager': self._fallback_manager,
        })
        if klass:
            klass = self._get_class(klass)
        else:
            klass = self.__class__
        return super(TranslationQueryset, self)._clone(klass, setup, **kwargs)
    
    def iterator(self):
        """
        If this queryset is not filtered by a language code yet, it should be
        filtered first by calling self.language.
        
        If someone doesn't want a queryset filtered by language, they should use
        Model.objects.untranslated()
        """
        if not self._language_code:
            for obj in self.language().iterator():
                yield obj
        else:
            for obj in super(TranslationQueryset, self).iterator():
                # non-cascade-deletion hack:
                if not obj.master:
                    yield obj
                else:
                    yield combine(obj, self.shared_model)


class TranslationManager(models.Manager):
    """
    Manager class for models with translated fields
    """
    #===========================================================================
    # API 
    #===========================================================================

    def using_translations(self):
        if not hasattr(self, '_real_manager'):
            self.contribute_real_manager()
        qs = TranslationQueryset(self.translations_model, using=self.db, real=self._real_manager)
        if hasattr(self, 'core_filters'):
            qs = qs._next_is_sticky().filter(**(self.core_filters))
        return qs.select_related('master')

    def language(self, language_code=None):
        return self.using_translations().language(language_code)

    def untranslated(self):
        return self._fallback_manager.get_query_set()

    #===========================================================================
    # Internals
    #===========================================================================

    @property
    def translations_model(self):
        """
        Get the translations model class
        """
        return self.model._meta.translations_model

    #def get_query_set(self):
    #    """
    #    Make sure that querysets inherit the methods on this manager (chaining)
    #    """
    #    return self.untranslated()
    
    def contribute_to_class(self, model, name):
        super(TranslationManager, self).contribute_to_class(model, name)
        self.name = name
        self.contribute_real_manager()
        self.contribute_fallback_manager()
        
    def contribute_real_manager(self):
        self._real_manager = models.Manager()
        self._real_manager.contribute_to_class(self.model, '_%s' % getattr(self, 'name', 'objects'))
    
    def contribute_fallback_manager(self):
        self._fallback_manager = TranslationFallbackManager()
        self._fallback_manager.contribute_to_class(self.model, '_%s_fallback' % getattr(self, 'name', 'objects'))


#===============================================================================
# Fallbacks
#===============================================================================

class FallbackQueryset(QuerySet):
    '''
    Queryset that tries to load a translated version using fallbacks on a per
    instance basis.
    BEWARE: creates a lot of queries!
    '''
    def __init__(self, *args, **kwargs):
        self._translation_fallbacks = None
        super(FallbackQueryset, self).__init__(*args, **kwargs)
    
    def _get_real_instances(self, base_results):
        """
        The logic for this method was taken from django-polymorphic by Bert
        Constantin (https://github.com/bconstantin/django_polymorphic) and was
        slightly altered to fit the needs of django-nani.
        """
        # get the primary keys of the shared model results
        base_ids = [obj.pk for obj in base_results]
        fallbacks = list(self._translation_fallbacks)
        # get all translations for the fallbacks chosen for those shared models,
        # note that this query is *BIG* and might return a lot of data, but it's
        # arguably faster than running one query for each result or even worse
        # one query per result per language until we find something
        translations_manager = self.model._meta.translations_model.objects
        baseqs = translations_manager.select_related('master')
        translations = baseqs.filter(language_code__in=fallbacks,
                                     master__pk__in=base_ids)
        fallback_objects = defaultdict(dict)
        # turn the results into a dict of dicts with shared model primary key as
        # keys for the first dict and language codes for the second dict
        for obj in translations:
            fallback_objects[obj.master.pk][obj.language_code] = obj
        # iterate over the share dmodel results
        for instance in base_results:
            translation = None
            # find the translation
            for fallback in fallbacks:
                translation = fallback_objects[instance.pk].get(fallback, None)
                if translation is not None:
                    break
            # if we found a translation, yield the combined result
            if translation:
                yield combine(translation, self.model)
            else:
                # otherwise yield the shared instance only
                logger.error("no translation for %s, type %s" % (instance, type(instance)))
                yield instance
        
    def iterator(self):
        """
        The logic for this method was taken from django-polymorphic by Bert
        Constantin (https://github.com/bconstantin/django_polymorphic) and was
        slightly altered to fit the needs of django-nani.
        """
        base_iter = super(FallbackQueryset, self).iterator()

        # only do special stuff when we actually want fallbacks
        if self._translation_fallbacks:
            while True:
                base_result_objects = []
                reached_end = False
                
                # get the next "chunk" of results
                for i in range(CHUNK_SIZE):
                    try:
                        instance = base_iter.next()
                        base_result_objects.append(instance)
                    except StopIteration:
                        reached_end = True
                        break
    
                # "combine" the results with their fallbacks
                real_results = self._get_real_instances(base_result_objects)
                
                # yield em!
                for instance in real_results:
                    yield instance
    
                # get out of the while loop if we're at the end, since this is
                # an iterator, we need to raise StopIteration, not "return".
                if reached_end:
                    raise StopIteration
        else:
            # just iterate over it
            for instance in base_iter:
                yield instance
    
    def use_fallbacks(self, *fallbacks):
        if fallbacks:
            self._translation_fallbacks = fallbacks
        else:
            self._translation_fallbacks = FALLBACK_LANGUAGES 
        return self

    def _clone(self, klass=None, setup=False, **kwargs):
        kwargs.update({
            '_translation_fallbacks': self._translation_fallbacks,
        })
        return super(FallbackQueryset, self)._clone(klass, setup, **kwargs)


class TranslationFallbackManager(models.Manager):
    """
    Manager class for the shared model, without specific translations. Allows
    using `use_fallbacks()` to enable per object language fallback.
    """
    def use_fallbacks(self, *fallbacks):
        return self.get_query_set().use_fallbacks(*fallbacks)
    
    def get_query_set(self):
        qs = FallbackQueryset(self.model, using=self.db)
        return qs


#===============================================================================
# TranslationAware
#===============================================================================


class TranslationAwareQueryset(QuerySet):
    def __init__(self, *args, **kwargs):
        super(TranslationAwareQueryset, self).__init__(*args, **kwargs)
        self._language_code = None
        
    def _translate_args_kwargs(self, *args, **kwargs):
        self.language(self._language_code)
        language_joins = []
        newkwargs = {}
        extra_filters = Q()
        for key, value in kwargs.items():
            newkey, langjoins = translate(key, self.model)
            for langjoin in langjoins:
                if langjoin not in language_joins:
                    language_joins.append(langjoin)
            newkwargs[newkey] = value
        newargs = []
        for q in args:
            new_q, langjoins = self._recurse_q(q)
            newargs.append(new_q)
            for langjoin in langjoins:
                if langjoin not in language_joins:
                    language_joins.append(langjoin)
        for langjoin in language_joins:
            extra_filters &= Q(**{langjoin: self._language_code})
        return newargs, newkwargs, extra_filters

    def _recurse_q(self, q):
        newchildren =  []
        language_joins = []
        for child in q.children:
            if isinstance(child, Q):
                newq = self._recurse_q(child)
                newchildren.append(self._recurse_q(newq))
            else:
                key, value = child
                newkey, langjoins =translate(key, self.model)
                newchildren.append((newkey, value))
                for langjoin in langjoins:
                    if langjoin not in language_joins:
                        language_joins.append(langjoin)
        q.children = newchildren
        return q, language_joins
    
    def _translate_fieldnames(self, fields):
        self.language(self._language_code)
        newfields = []
        extra_filters = Q()
        language_joins = []
        for field in fields:
            newfield, langjoins = translate(field, self.model)
            newfields.append(newfield)
            for langjoin in langjoins:
                if langjoin not in language_joins:
                    language_joins.append(langjoin)
        for langjoin in language_joins:
            extra_filters &= Q(**{langjoin: self._language_code})
        return newfields, extra_filters
    
    #===========================================================================
    # Queryset/Manager API 
    #===========================================================================
        
    def language(self, language_code=None):
        if not language_code:
            language_code = get_language()
        self._language_code = language_code
        return self
    
    def get(self, *args, **kwargs):
        newargs, newkwargs, extra_filters = self._translate_args_kwargs(*args, **kwargs)
        return self._filter_extra(extra_filters).get(*newargs, **newkwargs)

    def filter(self, *args, **kwargs):
        newargs, newkwargs, extra_filters = self._translate_args_kwargs(*args, **kwargs)
        return self._filter_extra(extra_filters).filter(*newargs, **newkwargs)

    def aggregate(self, *args, **kwargs):
        raise NotImplementedError()

    def latest(self, field_name=None):
        extra_filters = Q()
        if field_name:
            field_name, extra_filters = translate(self, field_name)
        return self._filter_extra(extra_filters).latest(field_name)

    def in_bulk(self, id_list):
        raise NotImplementedError()

    def values(self, *fields):
        fields, extra_filters = self._translate_fieldnames(fields)
        return self._filter_extra(extra_filters).values(*fields)

    def values_list(self, *fields, **kwargs):
        fields, extra_filters = self._translate_fieldnames(fields)
        return self._filter_extra(extra_filters).values_list(*fields, **kwargs)

    def dates(self, field_name, kind, order='ASC'):
        raise NotImplementedError()

    def exclude(self, *args, **kwargs):
        newargs, newkwargs, extra_filters = self._translate_args_kwargs(*args, **kwargs)
        return self._exclude_extra(extra_filters).exclude(*newargs, **newkwargs)

    def complex_filter(self, filter_obj):
        # admin calls this with an empy filter_obj sometimes
        if filter_obj == {}:
            return self
        raise NotImplementedError()

    def annotate(self, *args, **kwargs):
        raise NotImplementedError()

    def order_by(self, *field_names):
        """
        Returns a new QuerySet instance with the ordering changed.
        """
        fieldnames, extra_filters = self._translate_fieldnames(field_names)
        return self._filter_extra(extra_filters).order_by(*fieldnames)
    
    def reverse(self):
        raise NotImplementedError()

    def defer(self, *fields):
        raise NotImplementedError()

    def only(self, *fields):
        raise NotImplementedError()
    
    def _clone(self, klass=None, setup=False, **kwargs):
        kwargs.update({
            '_language_code': self._language_code,
        })
        return super(TranslationAwareQueryset, self)._clone(klass, setup, **kwargs)
    
    def _filter_extra(self, extra_filters):
        qs = super(TranslationAwareQueryset, self).filter(extra_filters)
        return super(TranslationAwareQueryset, qs)

    def _exclude_extra(self, extra_filters):
        qs = super(TranslationAwareQueryset, self).exclude(extra_filters)
        return super(TranslationAwareQueryset, qs)
    

class TranslationAwareManager(models.Manager):
    def language(self, language_code=None):
        return self.get_query_set().language(language_code)
        
    def get_query_set(self):
        qs = TranslationAwareQueryset(self.model, using=self.db)
        return qs


#===============================================================================
# Translations Model Manager
#===============================================================================


class TranslationsModelManager(models.Manager):
    def get_language(self, language):
        return self.get(language_code=language)