2017-09-29 53 views
0

我有models.py值錯誤:無法分配給查詢集屬性必須是實例

class employees(models.Model): 
    emp_id=models.PositiveIntegerField() 
    emp_name = models.CharField(max_length = 100) 
    emp_lname = models.CharField(max_length = 100) 
    emp_loc=models.CharField(max_length=5,choices=LOCATION) 
    manager_id=models.ForeignKey('self',null=True,blank=True) 

class leave(models.Model): 
    employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') 
    start_date = models.DateField() 
    end_date = models.DateField() 
    status=models.CharField(max_length=1,choices=LEAVE_STATUS,default='P') 
    ltype=models.CharField(max_length=2,choices=LEAVE_TYPE) 
    message=models.CharField(max_length=500,blank=True) 

class notify(models.Model): 
    sender_id=models.ForeignKey(leave, related_name='%(class)s_sendername') 
    receiver_id=models.ForeignKey(leave,related_name='%(class)s_receivername') 
    date_time=models.DateTimeField() 

我views.py

def accept(request): 
    approved_emp_id=leave.objects.filter(id=accept_id); 
approving_emp_id=leave.objects.filter(employee__emp_id=request.user.username); 
accept_notify=notify(sender_id=approving_emp_id, receiver_id=approved_emp_id,date_time=datetime.datetime.now(),viewed='N'); 
accept_notify.save() 

當我要救我收到值數據庫錯誤爲ValueError: Cannot assign "<QuerySet [<leave: 121-geeta-2017-10-04-2017-10-06-C-V-2017-09-27 07:48:36.288873+00:00>]>": "notify.sender_id" must be a "leave" instance.

我在哪裏出錯approving_emp_idapproved_emp_id都只是離開實例。

+1

使用'leave.objects.get()'而不是'leave.objects.filter()'。 –

回答

1

當參數應該是實例時,您正在傳遞QuerySet。 A QuerySet是實例列表。僅傳遞一個實例。使用leave.objects.get()而不是leave.objects.filter()

objects.get()返回單個實例,其中objects.filter()返回QuerySet

def accept(request): 
    approved_emp_id = leave.objects.get(id = accept_id) 
    approving_emp_id = leave.objects.get(employee__emp_id = request.user.username) 
    accept_notify = notify(sender_id = approving_emp_id, receiver_id = approved_emp_id, date_time = datetime.datetime.now(), viewed = 'N') 
    accept_notify.save() 

另一種方式是slicingQuerySet

def accept(request): 
    approved_emp_id = leave.objects.filter(id = accept_id)[0] 
    approving_emp_id = leave.objects.filter(employee__emp_id = request.user.username)[0] 
    accept_notify = notify(sender_id = approving_emp_id, receiver_id = approved_emp_id, date_time = datetime.datetime.now(), viewed = 'N') 
    accept_notify.save() 
相關問題