我正在开发一个用户上传文件的应用程序。用户选择一个“项目”来分配文件。每个项目都被分配一个“用户”和一个“编辑者”。上传文件后,我正在尝试根据“项目”中的“用户”设置文件的所有者。
项目模型:
class Project(models.Model):
projectCode = models.CharField(max_length=10)
projectName = models.CharField(max_length=100)
user = models.ForeignKey(
User, related_name="projects", on_delete=models.CASCADE, null=True)
editor = models.ForeignKey(
User, on_delete=models.CASCADE, null=True)
creationDate = models.DateTimeField(auto_now_add=True)
completedDate = models.DateTimeField(null=True, blank=True)
dueDate = models.DateTimeField(null=True, blank=True)
def __str__(self):
return f"{self.projectName}"
要上传的文件的模型:
class Completed(models.Model):
completed = models.BooleanField(default=False)
url = models.CharField(max_length=100)
handle = models.CharField(max_length=30)
filename = models.CharField(max_length=100)
size = models.IntegerField()
source = models.CharField(max_length=50)
uploadId = models.CharField(max_length=50)
originalPath = models.CharField(max_length=50)
owner = models.ForeignKey(
User, related_name="completed", on_delete=models.CASCADE, null=True)
project = models.ForeignKey(
Project, related_name="projectId", on_delete=models.SET_DEFAULT, default=1)
uploadDate = models.DateTimeField(auto_now_add=True)
editor = models.ForeignKey(
User, related_name="editor", on_delete=models.CASCADE, null=True)
def __str__(self):
return f"{self.filename}"
项目序列化器:
ProjectSerializer(serializers.ModelSerializer):
user = UserSerializer(read_only=True)
class Meta:
model = Project
fields = '__all__'
上传文件的序列化器:
class CompletedSerializer(serializers.ModelSerializer):
project = ProjectSerializer(read_only=True)
owner = UserSerializer(read_only=True)
editor = UserSerializer(read_only=True)
class Meta:
model = Completed
fields = '__all__'
最后,是上传文件的视图集:
class CompletedViewSet(viewsets.ModelViewSet):
permission_classes = [
permissions.IsAuthenticated
]
serializer_class = CompletedSerializer
def get_queryset(self):
queryset = Completed.objects.all().filter(Q(project__user=self.request.user)
| Q(project__editor=self.request.user))
return queryset
def perform_create(self, serializer):
serializer.save(
editor=self.request.user
owner=???????
)
如何根据Project模型中的“用户”保存所有者?