Django:涉及外键的查询

时间:2017-10-08 16:29:03

标签: django django-models

我有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)

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(auto_now_add=True)
 viewed=models.CharField(max_length=2)

我希望receiver_id的员工ID为receiver_id是外键...     当我查询         notify.objects.filter(receiver_id__employee__emp_id=1

我得到空的查询集,但我想要使用emp_id = 1的元组。

1 个答案:

答案 0 :(得分:0)

此处notify.objects.filter(receiver_id__employee__emp_id=1)请确保您已指定了emp_id字段,因为它不是自动增加的字段。

也试试

notify.objects.filter(receiver_id__employee__id=1)