Create a Rest Framework serializer class for a translated fields model.

    :param shared_model: The shared model.
    :type shared_model: :class:`parler.models.TranslatableModel`
173178
def create_translated_fields_serializer(shared_model, meta=None, related_name=None, **fields):
    
    if not related_name:
        translated_model = shared_model._parler_meta.root_model
    else:
        translated_model = shared_model._parler_meta[related_name].model

    # Define inner Meta class
    if not meta:
        meta = {}
    meta['model'] = translated_model
    meta.setdefault('fields', ['language_code'] + translated_model.get_translated_fields())

    # Define serialize class attributes
    attrs = {}
    attrs.update(fields)
    attrs['Meta'] = type('Meta', (), meta)

    # Dynamically create the serializer class
    return type('{0}Serializer'.format(translated_model.__name__), (serializers.ModelSerializer,), attrs)
1050572
def _validate_master(new_class):
    
    if not new_class.master or not isinstance(new_class.master, ForwardManyToOneDescriptor):
        raise ImproperlyConfigured("{0}.master should be a ForeignKey to the shared table.".format(new_class.__name__))

    remote_field = new_class.master.field.remote_field
    shared_model = remote_field.model

    meta = shared_model._parler_meta
    if meta is not None:
        if meta._has_translations_model(new_class):
            raise ImproperlyConfigured("The model '{0}' already has an associated translation table!".format(shared_model.__name__))
        if meta._has_translations_field(remote_field.related_name):
            raise ImproperlyConfigured("The model '{0}' already has an associated translation field named '{1}'!".format(shared_model.__name__, remote_field.related_name))

    return shared_model
912097
def _create_model_class(self, model):
        
        cls_name = model.replace('.', '_')
        # Hack for Python 2 (no need to do this for Python 3)
        if sys.version_info[0] < 3:
            if isinstance(cls_name, unicode):
                cls_name = cls_name.encode('utf-8')
        # Retrieve server fields info and generate corresponding local fields
        attrs = {
            '_env': self,
            '_odoo': self._odoo,
            '_name': model,
            '_columns': {},
        }
        fields_get = self._odoo.execute(model, 'fields_get')
        for field_name, field_data in fields_get.items():
            if field_name not in FIELDS_RESERVED:
                Field = fields.generate_field(field_name, field_data)
                attrs['_columns'][field_name] = Field
                attrs[field_name] = Field
        # Case where no field 'name' exists, we generate one (which will be
        # in readonly mode) in purpose to be filled with the 'name_get' method
        if 'name' not in attrs['_columns']:
            field_data = {'type': 'text', 'string': 'Name', 'readonly': True}
            Field = fields.generate_field('name', field_data)
            attrs['_columns']['name'] = Field
            attrs['name'] = Field
        return type(cls_name, (Model,), attrs)
333169
def model_fields(model, allow_pk=False, only=None, exclude=None,
                 field_args=None, converter=None):
    
    converter = converter or ModelConverter()
    field_args = field_args or {}

    model_fields = list(model._meta.sorted_fields)
    if not allow_pk:
        model_fields.pop(0)

    if only:
        model_fields = [x for x in model_fields if x.name in only]
    elif exclude:
        model_fields = [x for x in model_fields if x.name not in exclude]

    field_dict = {}
    for model_field in model_fields:
        name, field = converter.convert(
            model,
            model_field,
            field_args.get(model_field.name))
        field_dict[name] = field

    return field_dict
604153
def model_to_dict(instance, **options):
    ""

    options = _defaults(options)
    attrs = {}

    if options['prehook']:
        if isinstance(options['prehook'], collections.Callable):
            instance = options['prehook'](instance)
            if instance is None:
                return attrs

    # Items in the `fields` list are the output aliases, not the raw
    # accessors (field, method, property names)
    for alias in options['fields']:

        # Get the accessor for the object
        accessor = options['aliases'].get(alias, alias)

        # Create the key that will be used in the output dict
        key = options['prefix'] + alias

        # Optionally camelcase the key
        if options['camelcase']:
            key = convert_to_camel(key)

        # Get the field value. Use the mapped value to the actually property or
        # method name. `value` may be a number of things, so the various types
        # are checked below.
        value = get_field_value(instance, accessor,
                                allow_missing=options['allow_missing'])

        # Related objects, perform some checks on their options
        if isinstance(value, (models.Model, QuerySet)):
            _options = _defaults(options['related'].get(accessor, {}))

            # If the `prefix` follows the below template, generate the
            # `prefix` for the related object
            if '%(accessor)s' in _options['prefix']:
                _options['prefix'] = _options['prefix'] % {'accessor': alias}

            if isinstance(value, models.Model):
                if len(_options['fields']) == 1 and _options['flat'] \
                        and not _options['merge']:
                    value = list(serialize(value, **_options).values())[0]
                else:
                    # Recurse, get the dict representation
                    _attrs = serialize(value, **_options)

                    # Check if this object should be merged into the parent,
                    # otherwise nest it under the accessor name
                    if _options['merge']:
                        attrs.update(_attrs)
                        continue

                    value = _attrs
            else:
                value = serialize(value, **_options)

        attrs[key] = value

    # Apply post-hook to serialized attributes
    if options['posthook']:
        attrs = options['posthook'](instance, attrs)

    return attrs
1085604
def _set_translated_fields(self, language_code=None, **fields):
        
        objects = []  # no generator, make sure objects are all filled first
        for parler_meta, model_fields in self._parler_meta._split_fields(**fields):
            translation = self._get_translated_model(language_code=language_code, auto_create=True, meta=parler_meta)
            for field, value in six.iteritems(model_fields):
                setattr(translation, field, value)

            objects.append(translation)
        return objects
840273
def get_facet_objects_serializer(self, *args, **kwargs):
        
        facet_objects_serializer_class = self.get_facet_objects_serializer_class()
        kwargs["context"] = self.get_serializer_context()
        return facet_objects_serializer_class(*args, **kwargs)
946542
def field(name, *params)
      @model.translated_attribute_names.push name.to_sym
      @model.translated_attr_accessor(name)
      @model.translation_class.field name, *params
    end
879333
def get_cached_translated_field(instance, field_name, language_code=None, use_fallback=False):
    
    if language_code is None:
        language_code = instance.get_current_language()

    # In django-parler 1.1 the order of the arguments was fixed, It used to be language_code, field_name
    # This serves as detection against backwards incompatibility issues.
    if len(field_name) <= 5 and len(language_code) > 5:
        raise RuntimeError("Unexpected language code, did you swap field_name, language_code?")

    translated_model = instance._parler_meta.get_model_by_field(field_name)
    values = _get_cached_values(instance, translated_model, language_code, use_fallback)
    if not values:
        return None

    # Allow older cached versions where the field didn't exist yet.
    return values.get(field_name, None)
256930
def finish_multilingual_class(cls, *args, **kwargs):
        

        main_cls = kwargs['sender']
        translation_model_name = main_cls.__name__ + "Translation"

        # create the model with all the translatable fields
        unique = [('language_code', 'master')]
        for f in cls.get_unique_fields():
            unique.append(('language_code',f))

        class TransMeta:
            pass

        try:
            meta = cls.Meta
        except AttributeError:
            meta = TransMeta

        meta.ordering = ('language_code',)
        meta.unique_together = tuple(unique)
        meta.app_label = main_cls._meta.app_label
        if not hasattr(meta, 'db_table'):
            meta.db_table = main_cls._meta.db_table + '_translation'

        trans_attrs = cls.__dict__.copy()
        trans_attrs['Meta'] = meta
        # TODO: increase the length of this field, but to what???
        trans_attrs['language_code'] = models.CharField(max_length=15, blank=True,
                                                        choices=get_language_choices(),
                                                        db_index=True)
        
        related_name = getattr(meta, 'related_name', 'translations')
        if hasattr(meta, 'related_name'):
            delattr(meta, 'related_name')
        
        edit_inline = True

        trans_attrs['master'] = TranslationForeignKey(main_cls, blank=False, null=False,
                                                      related_name=related_name,)
        trans_attrs['__str__'] = lambda self: ("%s object, language_code=%s"
                                               % (translation_model_name,
                                                  self.language_code))

        trans_model = ModelBase(translation_model_name, (models.Model,), trans_attrs)
        trans_model._meta.translated_fields = cls.create_translation_attrs(main_cls)
        trans_model._meta.related_name = related_name

        _old_init_name_map = main_cls._meta.__class__.init_name_map
        def init_name_map(self):
            cache = _old_init_name_map(self)
            for name, field_and_lang_id in trans_model._meta.translated_fields.items():
                #import sys; sys.stderr.write('TM %r\n' % trans_model)
                cache[name] = (field_and_lang_id[0], trans_model, True, False)
            return cache
        main_cls._meta.init_name_map = instancemethod(init_name_map,
                                                      main_cls._meta,
                                                      main_cls._meta.__class__)

        main_cls._meta.translation_model = trans_model
        main_cls._meta.force_language = None
        main_cls.Translation = trans_model
        main_cls.get_translation = get_translation
        main_cls.fill_translation_cache = fill_translation_cache
1064024
def _get_fieldtranslations(instance, field=None, lang=None):
	

	# Basic filtering: filter translations by module, model an object_id
	_filter = {"module": instance.__module__, "model": instance.__class__.__name__, "object_id": instance.id}

	if lang:
		_filter["lang"] = lang

	# If we specify a field we get ONE translation (this field translation)
	if field:
		_filter["field"] = field
		try:
			return FieldTranslation.objects.get(**_filter)
		except FieldTranslation.DoesNotExist:
			return False

	# Otherwise, we get all translations
	return FieldTranslation.objects.filter(**_filter)
878489
def serialize(self, queryset, **options):
        
        self.options = options

        self.stream = options.pop("stream", six.StringIO())
        self.selected_fields = options.pop("fields", None)
        self.use_natural_foreign_keys = options.pop('use_natural_foreign_keys', False)
        self.use_natural_primary_keys = options.pop('use_natural_primary_keys', False)
        progress_bar = self.progress_class(
            options.pop('progress_output', None), options.pop('object_count', 0)
        )

        self.start_serialization()
        self.first = True
        for count, obj in enumerate(queryset, start=1):
            self.start_object(obj)
            # Use the concrete parent class' _meta instead of the object's _meta
            # This is to avoid local_fields problems for proxy models. Refs #17717.
            concrete_model = obj._meta.concrete_model
            for field in self.get_local_fields(concrete_model):
                if field.serialize:
                    if field.remote_field is None:
                        if self.selected_fields is None or field.attname in self.selected_fields:
                            self.handle_field(obj, field)
                    else:
                        if self.selected_fields is None or field.attname[:-3] in self.selected_fields:
                            self.handle_fk_field(obj, field)
            for field in self.get_local_m2m_fields(concrete_model):
                if field.serialize:
                    if self.selected_fields is None or field.attname in self.selected_fields:
                        self.handle_m2m_field(obj, field)
            self.end_object(obj)
            progress_bar.update(count)
            if self.first:
                self.first = False
        self.end_serialization()
        return self.getvalue()
374163
def serialize(cls, share_detail):
        

        return {
            cls._FIELD_PAYMENT: converter.serialize(
                share_detail._payment_field_for_request),
            cls._FIELD_READ_ONLY: converter.serialize(
                share_detail._read_only_field_for_request),
            cls._FIELD_DRAFT_PAYMENT: converter.serialize(
                share_detail._draft_payment
            ),
        }
700173
def get_translation_objects(self, request, language_code, obj=None, inlines=True):
        
        if obj is not None:
            # A single model can hold multiple TranslatedFieldsModel objects.
            # Return them all.
            for translations_model in obj._parler_meta.get_all_models():
                try:
                    translation = translations_model.objects.get(master=obj, language_code=language_code)
                except translations_model.DoesNotExist:
                    continue
                yield [translation]

        if inlines:
            for inline, qs in self._get_inline_translations(request, language_code, obj=obj):
                yield qs
628795
def deserialize(cls, target_class, obj):
        

        share_detail = target_class.__new__(target_class)
        share_detail.__dict__ = {
            cls._ATTRIBUTE_PAYMENT: converter.deserialize(
                object_.ShareDetailPayment,
                cls._get_field_or_none(cls._FIELD_DRAFT_PAYMENT, obj)
            ),
            cls._ATTRIBUTE_READ_ONLY: converter.deserialize(
                object_.ShareDetailReadOnly,
                cls._get_field_or_none(cls._FIELD_READ_ONLY, obj)
            ),
            cls._ATTRIBUTE_DRAFT_PAYMENT: converter.deserialize(
                object_.ShareDetailDraftPayment,
                cls._get_field_or_none(cls._FIELD_DRAFT_PAYMENT, obj)
            ),
        }

        return share_detail
270505
def mutable_model_prepared(signal, sender, definition, existing_model_class,
                           **kwargs):
    
    referenced_models = set()
    # Collect all model class the obsolete model class was referring to
    if existing_model_class:
        for field in existing_model_class._meta.local_fields:
            if isinstance(field, RelatedField):
                remote_field_model = get_remote_field_model(field)
                if not isinstance(remote_field_model, string_types):
                    referenced_models.add(remote_field_model)
    # Add sender as a dependency of all mutable models it refers to
    for field in sender._meta.local_fields:
        if isinstance(field, RelatedField):
            remote_field_model = get_remote_field_model(field)
            if not isinstance(remote_field_model, string_types):
                referenced_models.add(remote_field_model)
                if (issubclass(remote_field_model, MutableModel) and
                        remote_field_model._definition != sender._definition):
                    remote_field_model._dependencies.add(sender._definition)
    # Mark all model referring to this one as dependencies
    related_model_defs = ModelDefinition.objects.filter(
        Q(fielddefinitions__foreignkeydefinition__to=definition) |
        Q(fielddefinitions__manytomanyfielddefinition__to=definition)
    ).distinct()
    for model_def in related_model_defs:
        if model_def != definition:
            # Generate model class from definition and add it as a dependency
            sender._dependencies.add(model_def.model_class()._definition)
    # Clear the referenced models opts related cache
    for model_class in referenced_models:
        clear_opts_related_cache(model_class)
1267685
def add_translation_field(self, field, translation_field):
        
        self.local_fields[field].add(translation_field)
        self.fields[field].add(translation_field)