2

仅保存项目模型字段不创建项目文档模型字段

模型.py

类项目(BaseModel):

name = models.CharField(max_length=100, blank=True, null=True)
class Meta:
    db_table = 'project_details'
    ordering = ['is_active']  

类项目文档(BaseModel):

file = models.FileField(upload_to="files/%Y/%m/%d")
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='projectdocuments')
class Meta:
    db_table = 'project_document_details'
    ordering = ['is_active']           

视图.py:

def post(自我,请求,格式=无):

    user_id = request.user.id
    current_date = datetime.now()
    data = copy.deepcopy(request.data)
    file_fields = list(request.FILES.values())  # list to be passed to the serializer

    data['is_active'] = True
    data['created_by'] = user_id
    data['created_date'] = current_date
    data['modified_by'] = user_id
    data['modified_date'] = current_date
    serializer = ProjectSerializer(data=data, file_fields=file_fields)
    if serializer.is_valid():
        serializer.save()

序列化程序.py:

类 ProjectSerializer(serializers.ModelSerializer): def init (self, *args, **kwargs):

    file_fields = kwargs.pop('file_fields', None)
    super(ProjectSerializer, self).__init__(*args, **kwargs)
    if file_fields:
        field_update_dict = {str(field): serializers.FileField(required=False, write_only=True) for field in file_fields}
        print "FILE UPDATE DICT ------------>",field_update_dict
        self.fields.update(**field_update_dict)

def create(self, validated_data):
    validated_data_copy = validated_data.copy()
    validated_files = []
    for key, value in validated_data_copy.items():
        if isinstance(value, InMemoryUploadedFile):
            validated_files.append(value)
            validated_data.pop(key)
    submission_instance = super(ProjectSerializer, self).create(validated_data)
    for file in validated_files:
        ProjectDocuments.objects.create(submission=submission_instance, file=file)
    return submission_instance

class Meta:
    model = Project
    fields = '__all__'
4

0 回答 0