我们从Python开源项目中,提取了以下14个代码示例,用于说明如何使用django.forms.model_to_dict()。
def get_questions_of_group(self): gid = self.request_params.get('gid') question_group = models.QuestionGroup.objects.filter( pk=gid, deleted=False).first() if not question_group: return self.json_res(ok=False, code=1, msg="[404]??????") group_dict = self.group_serializer.to_representation(question_group) questions = question_group.questions.filter( deleted=False).order_by('pk') ql = [] for q in questions: q_dict = self.question_serializer.to_representation(q) q_opts = q.questionoption_set.all().order_by('pk') opt_list = [model_to_dict(o, ['id', 'text']) for o in q_opts] q_dict['options'] = opt_list ql.append(q_dict) group_dict['questions'] = ql return self.json_res(data=group_dict)
def __init__(self, form, field, name): super().__init__(form, field, name) ArrayFormSet = forms.formset_factory(field.model_form_class, can_delete=True) data = self.data if form.is_bound else None initial = [] if self.initial is not None: for ini in self.initial: if isinstance(ini, Model): initial.append( forms.model_to_dict( ini, fields=field.model_form_class._meta.fields, exclude=field.model_form_class._meta.exclude )) self.form_set = ArrayFormSet(data, initial=initial, prefix=name)
def _copy(self, id): from django.forms import model_to_dict instance = ScoreEnjoy.objects.get(id=id) kwargs = model_to_dict(instance, exclude=['id', 'status']) new_instance = ScoreEnjoy.objects.create(**kwargs) # copy targets targets = ScoreEnjoy.objects.filter(bkp_pic_id=id).all() for t in targets: t.id = None t.bkp_pic_id = new_instance.id t.save() return ('msg', '????')
def _copy(self, id): from django.forms import model_to_dict instance = BKPPic.objects.get(id=id) kwargs = model_to_dict(instance, exclude=['id', 'status']) new_instance = BKPPic.objects.create(**kwargs) # copy targets targets = BKPTarget.objects.filter(bkp_pic_id=id).all() for t in targets: t.id = None t.bkp_pic_id = new_instance.id t.save() return ('msg', '????')
def serialize_model_instance(instance): """Serialize an instance model as a Python dict. :param instance: Instance model. :type instance: object :return: Instance serialized. :rtype: dict """ d = model_to_dict(instance) return {k: _adapt(v) for k, v in d.iteritems()}
def user_to_dict(user): """ ????? ?????????? ? ????? ? ???????, ????????? ??? JSON """ user_dict = model_to_dict(user, fields=( 'id', 'email', 'username', 'first_name', 'last_name', 'is_staff', 'is_superuser' )) user_dict.update(avatar={ name: getattr(user.avatar, name).url for name in user.avatar.variations if hasattr(user.avatar, name) }) return user_dict
def model_to_dict(instance, fields=None, exclude=None): """ Similar to the model_to_dict of the Django ORM but it supports also instance to be of type restframeworkclient.Model """ if isinstance(instance, Model): return {k: v for k, v in instance._attrs.items() if (not fields or k in fields) and (not exclude or k not in exclude)} else: result = django_model_to_dict(instance, fields=fields, exclude=exclude) return result
def assertCommEqual(self, expected: List[models.Communicatiegegevens], cgs: List[models.Communicatiegegevens]): expected_dicts = [model_to_dict(m, exclude='id') for m in expected] given_dicts = [model_to_dict(m, exclude='id') for m in cgs] self.assertListEqual(expected_dicts, given_dicts)
def assertActEqual(self, expected: List[models.Activiteit], given: List[models.Activiteit]): expected_dicts = [model_to_dict(m, exclude='id') for m in expected] given_dicts = [model_to_dict(m, exclude='id') for m in given] self.assertListEqual(expected_dicts, given_dicts)
def has_changed(self, initial, data): form_set_initial = [] for init in initial: form_set_initial.append( forms.model_to_dict( init, fields=self.model_form_class._meta.fields, exclude=self.model_form_class._meta.exclude ) ) form_set = self.ArrayFormSet(data, initial=form_set_initial, prefix=self.name) return form_set.has_changed()
def getTaxIdAndDateByToken( token ): try: clientRequests = ClientRequests.objects.filter( token=token ) if clientRequests: clientRequest = clientRequests.values()[0] if clientRequest['taxId'] is not 0: return clientRequest['taxId'], clientRequest['date'] receipt = clientRequest['receipt'] date = clientRequest['date'] if receipt and date: task = getTaskObject( receipt , date ) task = model_to_dict( task ) taskId = task['id'] statistics = TaskStatistics.objects.filter( task=taskId ) if statistics: taxId = statistics.values()[0]['taxId'] clientRequest.update( taxId=taxId ) return taxId, date except Exception, e: dblog.error( str(e) ) return 0, None
def _copy(self, id): from django.forms import model_to_dict instance = BKPLevel.objects.get(id=id) kwargs = model_to_dict(instance, exclude=['id', 'status']) new_instance = BKPLevel.objects.create(**kwargs) return ('msg', '????')
def _copy(self, id): instance = BalloonSubLevel.objects.filter(id=id).get(id=id) kwargs = model_to_dict(instance, exclude=['id', 'status']) new_instance = BalloonSubLevel.objects.create(**kwargs) # copy oct oct = BalloonSubLevelOctave.objects.filter(sub_level_id=id).all() for t in oct: t.id = None t.sub_level_id = new_instance.id t.save()
def edit_target(self, data): save_target_extern_info = {} bkp_pic_id = data.get('pic_id') namel = data.getlist('target_name') top_left_xl = data.getlist('top_left_x') top_left_yl = data.getlist('top_left_y') bottom_right_xl = data.getlist('bottom_right_x') bottom_right_yl = data.getlist('bottom_right_y') target_key = ['name', 'top_left_x', 'top_left_y', 'bottom_right_x', 'bottom_right_y'] # ??????????target ??picid ?? ?????????? ??? obj = BKPTarget.objects.filter(bkp_pic_id=bkp_pic_id) save_target_extern_info = obj.exclude(Q(target_audio_path='') | Q(desc_audio_path='')).values('name', 'target_audio_name', 'target_audio_path', 'desc_audio_name', 'desc_audio_path', 'description').distinct() # ?? queryset ?? obj.delete() ??????? save_target_extern_info ?? # model_to_dict() ???? ?????meta fix keep = [] for k in save_target_extern_info: keep.append(k) # keep = model_to_dict(save_target_extern_info) if obj.count() > 0: # ??????????????????????????? ?? ?,{ }? # save_target_extern_info = obj.exclude(Q(target_audio_path='') | Q(desc_audio_path='')).values('name','target_audio_name', 'target_audio_path', 'desc_audio_name', 'desc_audio_path', 'description').distinct() # save_target_extern_info = copy.deepcopy(save_target_extern_info) # ???????? ?????????????? ???????????? # save_target_extern_info = self.save_target_extern_info(model_to_dict(obj.distinct('name').all())) # print 'save target extern info',save_target_extern_info obj.delete() # ??????target pic——ID???? for item in zip(namel, top_left_xl, top_left_yl, bottom_right_xl, bottom_right_yl): update = dict(zip(target_key, item)) update['bkp_pic_id'] = bkp_pic_id if keep: # ?????else ?? fix this print 'find it', self._find_extern_target_info(keep, update['name']) update.update(self._find_extern_target_info(keep, update['name'])) else: update.update(self.get_target_extern_info(update['name'])) target = BKPTarget.objects.create(**update) if target: pass # print 'save target', target.id