django는 모델에 따라 Serializer를 생성합니다

2370 단어 django
import re


model_str = '''
class Type(models.Model):
    name = models.CharField('    ', max_length=100)

    def __str__(self):
        return "%s" % self.name

    def natural_key(self):
        return (self.name)
'''
class_name = ''
col_name_list = []
model_str_list = model_str.split(':')
# print(model_str_list[0])
temp_class =  model_str_list[0]
matchObj = re.match( r".*class (.*)\(models.Model", model_str, re.M|re.I|re.S)
if matchObj:
    print(matchObj.group(1))
    class_name = matchObj.group(1)
else:
    print("not found")

# print(model_str_list[1])
row_list = model_str_list[1].split("
") for _ in row_list: if "=" in _: # print(_) = models. matchObj = re.match(r"(.*) = models\.", _, re.M | re.I | re.S) if matchObj: print(matchObj.group(1)) col_name_list.append(matchObj.group(1).replace(' ','')) fields_str = "(" update_str = "" for _ in col_name_list: update_str += "instance." + _ + " = validated_data.get(\'" + _ + "\',instance." + _ + ")
\t\t" if fields_str[-1] == '(': fields_str += "\'"+ _ +"\'" else: fields_str += ",\'" + _ + "\'" fields_str+= ')' # ----------------------------- start ------------------------------------------- print('----------------------------- start -------------------------------------------') print('----------------------------- start -------------------------------------------') print('class '+ class_name +'Serializer(serializers.ModelSerializer):') print("\ class Meta:
\ model = "+ class_name +"#
\ fields = "+ fields_str ) print("
\ def create(self,validated_data):
\ # , `"+class_name+"` 。
\ return "+ class_name +".objects.create(**validated_data)
\ ") print("
\ def update(self,instance,validated_data):
\ # , `"+ class_name +"` 。
\ "+ update_str + "instance.save()
\t\t\ return instance
\ ")

좋은 웹페이지 즐겨찾기