使用related_name返回查询集在Django中不起作用?

时间:2019-09-26 06:31:49

标签: python django django-views foreign-keys

这里我正在使用两个模型。两个模型都与ForeignKey模型具有User关系。在这里,我想查询staffsis_reviewed_bysent_by,并尝试这样做。当我进行过滤时,它返回查询集,但是当我使用related_name进行查询时,它将抛出AttributeError

我该怎么做?

  

`异常值:   '离开'对象没有属性'reviewed_by

models.py

class Leave(models.Model):
    staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff_leave')
    organization = models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='staff_leave')
    sub = models.CharField(max_length=300)
    msg = models.TextField()
    start_day = models.DateField()
    end_day = models.DateField()
    is_reviewed_by = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='reviewed_by',blank=True,null=True)

class LeaveReply(models.Model):
    staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='leave_status')
    leave = models.ForeignKey(Leave,on_delete=models.CASCADE,related_name='leave_status')
    sub = models.CharField(max_length=300,blank=True,null=True)
    msg = models.TextField(blank=True,null=True)
    sent_on = models.DateTimeField(auto_now_add=True)
    sent_by = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='sent_by')

views.py

def leave_detail(request, pk):
    leave = get_object_or_404(Leave, pk=pk)
    reviewers = leave.reviewed_by.all() # not working
    staffs = leave.staff_leave.all() # does not works

    staffs = Leave.objects.filter(staff=leave.staff) # this works
    reviewers = Leave.objects.filter(is_reviewed_by=leave.is_reviewed_by)  # works

    reply_sender = LeaveReply.objects.filter(sent_by=leave.is_reviewed_by) #works 

    reply_sender = leave.sent_by.all() # doesn't works

2 个答案:

答案 0 :(得分:0)

修改后的答案

型号:

class Leave(models.Model):
    staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff_leave')
    organization = models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='staff_leave')  
    is_reviewed_by = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='reviewed_by',blank=True,null=True) 

我认为此模型用于员工的请假详细信息。

无效代码:

reviewers = leave.reviewed_by.all() # not working
staffs = leave.staff_leave.all() # does not works

这是给休假的人员和审查休假申请的人员的。这两个字段都与用户模型有关。如果我们有Leave模型的实例(即leave = get_object_or_404(Leave, pk=pk)),则可以通过以下方式获得这两个:

staffs = leave.staff # for person who will be on leave
reviewers = leave.is_reviewed_by # for the person who reviewed the leave

额外

如果我们有一个 User 实例(user = get_object_or_404(User, pk=pk)),并且我们想知道他已经摘了多少叶子,那么我们可以使用相关名称:

no_of_leaves_itaken = user.staff_leave.all()

或他评论了多少张叶子:

no_of_leaves_reviewed = user.staff_leave.all()

答案 1 :(得分:0)

您有点困惑。此处与related_name无关。

您有一个Leave对象。如错误所述,请假项目没有reviewed_bysent_bystaff_leave属性。他们有is_reviewed_bystaff;并且唯一的sent_by对象在LeaveReply对象上。