Set a many-to-many field on an object
172062
def set_relation_many_to_many(self, obj, field_name, objs):
        ""
        relation = getattr(obj, field_name)
        if hasattr(relation, 'set'):
            relation.set(objs) # Django 2.x
        else:
            setattr(obj, field_name, objs)
328874
def get_fk_many_from_list(
            self, object_list, fkmany, fkmany_class, key_attr):
        """"""

        object_dict = {o.get(key_attr): o for o in object_list}
        object_keys = [o.get(key_attr) for o in object_list]

        # delete fks that have been removed
        fkmany = [o for o in fkmany if getattr(o, key_attr) in object_keys]

        # sync existing fks
        for fk in fkmany:
            obj = object_dict.get(getattr(fk, key_attr))
            for attr in fkmany_class.update_from_object_fields:
                setattr(fk, attr, obj.get(attr))

        # create new fks
        new_fks = []
        orm_keys = [getattr(o, key_attr) for o in fkmany]
        for obj in object_list:
            key = obj.get(key_attr)
            if key not in orm_keys:
                del obj['id']
                orm_kwargs = {}
                for k in obj:
                    if (
                        k in fkmany_class.update_from_object_fields and
                        k in obj
                    ):
                        orm_kwargs[k] = obj[k]
                new_obj = fkmany_class(**orm_kwargs)
                new_fks.append(new_obj)
        fkmany += new_fks
        return fkmany
470156
def _SetField(self, args, type_info, value):
    """"""
    if hasattr(type_info, "enum"):
      try:
        coerced_obj = type_info.enum[value.upper()]
      except KeyError:
        # A bool is an enum but serializes to "1" / "0" which are both not in
        # enum or reverse_enum.
        coerced_obj = type_info.type.FromHumanReadable(value)
    else:
      coerced_obj = type_info.type.FromHumanReadable(value)
    args.Set(type_info.name, coerced_obj)
1285080
def set_many(self, nodes):
        
        data = self._prepare_nodes(nodes)
        self._set_many(data)
1360192
private void setField(Field field, Object targetObject, Object value) throws UnmarshalException{
		field.setAccessible(true);
		try {
			field.set(targetObject, value);
		} catch (IllegalArgumentException e) {
			throw new UnmarshalException(e);
		} catch (IllegalAccessException e) {
			throw new UnmarshalException(e);
		}
	}
246417
private static void setField(Object object, Object value, Field foundField) {
        foundField.setAccessible(true);
        try {
            int fieldModifiersMask = foundField.getModifiers();
            removeFinalModifierIfPresent(foundField);
            foundField.set(object, value);
            restoreModifiersToFieldIfChanged(fieldModifiersMask, foundField);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Internal error: Failed to set field in method setInternalState.", e);
        }
    }
272972
function selectFields(obj, fields) {
  const result = {}
  if (obj) {
    fields.forEach(x => obj.hasOwnProperty(x) ? result[x] = obj[x] : null)
  }
  return result
}
615414
function(field, value) {
    var tmp = this.callParent(field, value)

    if (typeof field === 'object') {
      this.relations = this.relations || {}

      Object.keys(this.definition.relations).forEach(function(relationName) {
        if (field[relationName] !== undefined)
          this[relationName] = field[relationName]
      }, this)
    }

    return tmp
  }
343420
def _set_field_on_message(msg, key, value):
    """"""
    # Attempt to set the value on the types of objects we know how to deal
    # with.
    if isinstance(value, (collections_abc.MutableSequence, tuple)):
        # Clear the existing repeated protobuf message of any elements
        # currently inside it.
        while getattr(msg, key):
            getattr(msg, key).pop()

        # Write our new elements to the repeated field.
        for item in value:
            if isinstance(item, collections_abc.Mapping):
                getattr(msg, key).add(**item)
            else:
                # protobuf's RepeatedCompositeContainer doesn't support
                # append.
                getattr(msg, key).extend([item])
    elif isinstance(value, collections_abc.Mapping):
        # Assign the dictionary values to the protobuf message.
        for item_key, item_value in value.items():
            set(getattr(msg, key), item_key, item_value)
    elif isinstance(value, message.Message):
        getattr(msg, key).CopyFrom(value)
    else:
        setattr(msg, key, value)
1255585
def __objecthasfields(bunchdt, data, commdct, idfobject, places=7, **kwargs):
    """"""
    for key, value in list(kwargs.items()):
        if not isfieldvalue(
                bunchdt, data, commdct,
                idfobject, key, value, places=places):
            return False
    return True
261967
def to_set_field(cls):
    
    class SetConverter(object):

        def __init__(self, cls):
            self._cls = cls

        @property
        def cls(self):
            return resolve_class(self._cls)

        def __call__(self, values):
            values = values or set()
            args = {to_model(self.cls, value) for value in values}
            return TypedSet(cls=self.cls, args=args)

    return SetConverter(cls)
912480
private static void setFields(final Object from, final Object to,
	                              final Field[] fields, final boolean accessible,
	                              final Map objMap, final Map metadataMap)
	{
		for (int f = 0, fieldsLength = fields.length; f < fieldsLength; ++f)
		{
			final Field field = fields[f];
			final int modifiers = field.getModifiers();
			if ((Modifier.STATIC & modifiers) != 0) continue;
			if ((Modifier.FINAL & modifiers) != 0)
				throw new ObjectCopyException("cannot set final field [" + field.getName() + "] of class [" + from.getClass().getName() + "]");
			if (!accessible && ((Modifier.PUBLIC & modifiers) == 0))
			{
				try
				{
					field.setAccessible(true);
				}
				catch (SecurityException e)
				{
					throw new ObjectCopyException("cannot access field [" + field.getName() + "] of class [" + from.getClass().getName() + "]: " + e.toString(), e);
				}
			}
			try
			{
				cloneAndSetFieldValue(field, from, to, objMap, metadataMap);
			}
			catch (Exception e)
			{
				throw new ObjectCopyException("cannot set field [" + field.getName() + "] of class [" + from.getClass().getName() + "]: " + e.toString(), e);
			}
		}
	}
768373
private static function appendMany($manyList, $dataList, $fields, $modelClass)
    {
        foreach($dataList as $row)
        {
            $tmpRow = [];
            foreach($fields as $alias => $fieldName)
            {
                $tmpRow[$fieldName] = $row[$alias];
            }
            $manyList->append($modelClass::newInstance($tmpRow));
        }
    }
521406
def set_many(self, mapping, timeout=None):
        
        for key, value in _items(mapping):
            self.set(key, value, timeout)
857953
def formfield_for_manytomany(self, db_field, request, **kwargs):
        '''
        
        '''
        db = kwargs.get('using')
        kwargs['queryset'] = kwargs.get('queryset', self.get_field_queryset(db, db_field, request))
        return super(AccessControlMixin, self).formfield_for_manytomany(db_field, request, **kwargs)
547793
def insert_many(objects, using="default"):
    
    if not objects:
        return

    import django.db.models
    from django.db import connections
    from django.db import transaction
    con = connections[using]

    model = objects[0].__class__
    fields = [f for f in model._meta.fields
              if not isinstance(f, django.db.models.AutoField)]
    parameters = []
    for o in objects:
        params = tuple(f.get_db_prep_save(f.pre_save(o, True), connection=con)
                       for f in fields)
        parameters.append(params)

    table = model._meta.db_table
    column_names = ",".join(con.ops.quote_name(f.column) for f in fields)
    placeholders = ",".join(("%s",) * len(fields))
    con.cursor().executemany("insert into %s (%s) values (%s)"
                             % (table, column_names, placeholders), parameters)
    transaction.commit_unless_managed(using=using)
790072
def p_object_field_list(self, p):
        
        obj = p[1].copy()
        obj.update(p[2])
        p[0] = obj