如何从Django的外键模型获取ID

时间:2019-11-17 16:54:25

标签: django python-3.6

如何从以下模型中获取to_user的ID:

class Friend(models.Model):
     status = models.CharField(max_length=10)
     from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user')
     to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="to_user")
     date_modified = models.DateTimeField(auto_now=True, blank=True)
     date_created = models.DateTimeField(auto_now_add=True, null=True)

     def create(self,request, **kwargs, ):
         friend = self.create(from_user_id=request.user.id, status="Pending")
         return friend

    class Meta:
        unique_together = (('from_user', 'to_user'),)

    def __str__(self):
        return self.to_user.email

我的观点:

def accept_friend_request(request, uidb64, status):
     """Accept button will lead to entry in database as accepted and reject button will lead to entry in database as rejected  based on status flag"""
      Friend.status = "pending"
      try:
         uid = urlsafe_base64_decode(uidb64)
         friend_user = User.objects.filter(id=Friend.to_user.id)
         f = Friend.objects.filter(friend_id = friend_user)
         if f:
             f.status=status
             f.save()
             f.status = "accepted"
            return render(request, 'users/friend_list.html', {"uidb64": uid, "status": status})
          else:
             f.status = "rejected"
             f.save()
             return render(request, 'users/friend_list.html', {'uidb64':uid, 'status':status})
      except AttributeError:
          return render(request, 'blog/base.html')

我无法检索到friend_user = User.objects.filter(id = Friend.to_user.id)

先谢谢您

1 个答案:

答案 0 :(得分:2)

Friend是一个模型类,您需要此类的一个实例才能将它作为外部关系与另一个模型实例相关。

例如:

friend_instance = Friend.objects.get(name='Madeleaine')
...
friend_user = friend_instance.to_user.id