【发布时间】:2018-12-30 23:24:30
【问题描述】:
使用filter(),我如何获取当前认证用户的外键属性'recipient'?
模型.py:
class Message(models.Model):
recipient = models.ForeignKey(CustomUser, on_delete = models.CASCADE,related_name = 'recipient',null = True)
sender = models.ManyToManyField(CustomUser,related_name = 'messages')
date = models.DateTimeField(auto_now_add=True, blank=True)
subject = models.CharField(max_length = 1000, blank = True)
message = models.TextField(blank=True, null=True)
unread = models.BooleanField(default = True)
class CustomUser(User):
user_bio = models.TextField(blank=True, null=True)
birth_date = models.DateField(null=True, blank=True)
def __str__(self):
return self.username
Views.py:
### Inbox list class
class InboxListView(ListView):
'''
This view lets the user view all the messages created in a list
'''
model = Message# [Message,SafeTransaction] # I want to be able to draw from two models/objects #
template_name = "myInbox/inbox.html"
paginate_by = 5
def get_context_data(self, **kwargs):
context = super(InboxListView, self).get_context_data(**kwargs)
context['message_list'] = Message.objects.filter(recipient=CustomUser.SOMETHING_idk)#INCORRECT FILTRATION, FIX ASAP!!!!!!!!!!!!!#
context['now'] = timezone.now()
context['safeTransaction_list'] = SafeTransaction.objects.all()
return context
特别是这一行是我需要困惑的:
context['message_list']=Message.objects.filter(recipient=CustomUser.SOMETHING_idk)
我可以将什么作为特定邮件收件人的过滤器参数? 我尝试了一些类似 CustomUser 或 CustomUser.pk 或 request.authenticated_as_the_thing_I_want_specifically 的方法。等等。
我好像有点迷茫了。
感谢任何帮助。
【问题讨论】:
-
所以你使用
CustomUser作为你的认证用户? -
self.request.user的类型是什么?
标签: django django-models filtering