django 如何从用户的个人资料中获取用户查询集

zsbz8rwp  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(96)

下午好。我正在创建一个推荐系统,在最后阶段出现了一个问题。我需要为Friends.create.objects获取request.User和inviting.User查询集(inviting=current_user,invited=inviting_query.user)
我怎么得到他们?
我的模特:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    invite_code = models.CharField(max_length=6, unique=True)
    was_invited = models.BooleanField(default=False)

class Friends(models.Model):
    inviting = models.ForeignKey(User, on_delete=models.CASCADE, related_name='invited')
    # кого пригласили
    invited = models.ForeignKey(User, on_delete=models.CASCADE, related_name='invinting')
    # кто пригласил

字符串
岗位职能:

def post(self, request: HttpRequest) -> HttpResponse:
        invite_code = request.POST['invite_code']

        invited_user = Profile.objects.filter(invite_code=invite_code)
        current_user = request.user

        Friends.objects.create(inviting=current_user, invited=invited_user)

        return render(request, 'api_auth_user/user-profile.html')

rslzwgfq

rslzwgfq1#

您可以使用Profileuser,因此:

from django.shortcuts import get_object_or_404

def post(self, request: HttpRequest) -> HttpResponse:
    invite_code = request.POST['invite_code']

    invited_user_id = get_object_or_404(Profile, invite_code=invite_code)
    current_user = request.user

    Friends.objects.create(
        inviting=request.user, invited_id=invited_user_id.user_id
    )

    return render(request, 'api_auth_user/user-profile.html')

字符串
然而,Profile有一个邀请码看起来很奇怪,这意味着每个用户都有一个可以被每个人使用的邀请码?

相关问题