Django 更新或创建 - 预保存

发布于 2025-01-12 05:35:19 字数 1744 浏览 0 评论 0原文

我正在努力解决一个可能很简单的问题。我正在尝试创建记录或更新(如果已有记录)。我正在尝试覆盖模型保存功能。该标准基于是否有用户已经拥有其 exp_type 的答案。如果有的话我想更新它,如果没有的话我想创建它。

这是我所拥有的:

class UserExperienceTypeAnswer(TimeStampedModel):
    NA, NONE, SOME, LOTS, EXPERT = range(5)
    ANSWER_CHOICES = {
        (NA, "Not interested"),
        (NONE, "None"),
        (SOME, "Some"),
        (LOTS, "Lots"),
        (EXPERT, "Expert"),
    }

    user = models.ForeignKey(User, models.CASCADE, null=False, blank=False)
    exp_type = models.ForeignKey(
        RecruitmentExperienceType, models.CASCADE, null=False, blank=False
    )
    answer = models.PositiveSmallIntegerField(
        choices=ANSWER_CHOICES, default=NONE, blank=False, null=False
    )

    unique_together = ["user", "exp_type"]

    def save(self, *args, **kwargs):
        record = UserExperienceTypeAnswer.objects.filter(
            user=self.user, exp_type=self.exp_type
        ).first()

        if not record:
            super(UserExperienceTypeAnswer, self).save(*args, **kwargs)
        else:
            //This is the part im unsure of. I tried to save the record from query above
            record.answer = self.answer
            super(UserExperienceTypeAnswer, record).save(*args, **kwargs)
            // This gives duplicate key error (which i assume is because its trying to create new record)
           
            // I also tried to create model directly but this creates recursion error (as i assume i am calling this method on save in infinate loop. 
            UserExperienceTypeAnswer.objects.create(
                 user=self.user, exp_type=self.exp_type, answer=self.answer
            )

编辑:如果问题不清楚。

如果根据 exp_type 和用户过滤器记录不存在,我想创建一条新记录。如果确实存在,则使用新答案更新并保存现有记录。

I am struggling with what may be a simple issue. I am trying to create a record or update if there is already an existing record in place. I am trying to override the models save function. The criteria is based on is there a user that already has an answer for their exp_type. I wanted to update it if so, if not then i want to create it.

Here is what i have:

class UserExperienceTypeAnswer(TimeStampedModel):
    NA, NONE, SOME, LOTS, EXPERT = range(5)
    ANSWER_CHOICES = {
        (NA, "Not interested"),
        (NONE, "None"),
        (SOME, "Some"),
        (LOTS, "Lots"),
        (EXPERT, "Expert"),
    }

    user = models.ForeignKey(User, models.CASCADE, null=False, blank=False)
    exp_type = models.ForeignKey(
        RecruitmentExperienceType, models.CASCADE, null=False, blank=False
    )
    answer = models.PositiveSmallIntegerField(
        choices=ANSWER_CHOICES, default=NONE, blank=False, null=False
    )

    unique_together = ["user", "exp_type"]

    def save(self, *args, **kwargs):
        record = UserExperienceTypeAnswer.objects.filter(
            user=self.user, exp_type=self.exp_type
        ).first()

        if not record:
            super(UserExperienceTypeAnswer, self).save(*args, **kwargs)
        else:
            //This is the part im unsure of. I tried to save the record from query above
            record.answer = self.answer
            super(UserExperienceTypeAnswer, record).save(*args, **kwargs)
            // This gives duplicate key error (which i assume is because its trying to create new record)
           
            // I also tried to create model directly but this creates recursion error (as i assume i am calling this method on save in infinate loop. 
            UserExperienceTypeAnswer.objects.create(
                 user=self.user, exp_type=self.exp_type, answer=self.answer
            )

Edit: In case question is not clear.

I want to create a new record if record does not exist based on exp_type and user filter. If it does exist, then update and save that existing record with new answer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦在夏天 2025-01-19 05:35:19

根据 Christophes 的建议,我将其添加到视图集中,如下所示。它是一个 DRF 视图,所以我使用了 create 函数。

class UserExperienceTypeAnswerViewset(viewsets.ModelViewSet):

    queryset = models.UserExperienceTypeAnswer.objects.all().order_by("id")
    serializer_class = serializers.UserExperienceTypeAnswerSerializer

    filterset_fields = {
        "id": ("exact",),
        "user": ("exact",),
    }

    def create(self, request, *args, **kwargs):
        record = models.UserExperienceTypeAnswer.objects.filter(
            user=request.data["user"], exp_type=request.data["exp_type"]
        ).first()

        if not record:
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
        else:
            record.answer = request.data["answer"]
            record.save()
            serializer = self.get_serializer(record)

        return Response(serializer.data, status=status.HTTP_201_CREATED)

As per Christophes suggestion, I added this to viewset instead as below. Its a DRF view so I used the create function.

class UserExperienceTypeAnswerViewset(viewsets.ModelViewSet):

    queryset = models.UserExperienceTypeAnswer.objects.all().order_by("id")
    serializer_class = serializers.UserExperienceTypeAnswerSerializer

    filterset_fields = {
        "id": ("exact",),
        "user": ("exact",),
    }

    def create(self, request, *args, **kwargs):
        record = models.UserExperienceTypeAnswer.objects.filter(
            user=request.data["user"], exp_type=request.data["exp_type"]
        ).first()

        if not record:
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
        else:
            record.answer = request.data["answer"]
            record.save()
            serializer = self.get_serializer(record)

        return Response(serializer.data, status=status.HTTP_201_CREATED)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文