Django LEFT JOIN - 一对多

时间:2016-11-21 06:35:32

标签: python django django-models orm

我有以下型号:

class Employee(models.Model):

    def getFullname(self):
        return '{}, {} {}'.format(self.empLastname,self.empFirstname, self.empMiddlename)

    empID = models.CharField(primary_key=True, max_length= 50, null=False)
    empLastname = models.CharField(max_length=50)
    empFirstname = models.CharField(max_length=50)
    empMiddlename = models.CharField(max_length=50, null=True)
    fullname = property(getFullname)

    def __str__(self):
       return self.fullname

class Picture(models.Model):
    empID = models.ForeignKey(Employee, related_name="pictures", to_field='empID', on_delete = models.CASCADE)
    picture = models.ImageField('Uploaded image')
    isDef = models.BooleanField(default=False)

我想查询图片模型中isDefault=True的所有员工。但并非所有员工都有照片。所以基本上我想查询所有员工isDefault=True和所有没有图片的员工。

我的查询如下:

SELECT manager_employee.`*`, manager_picture.*
FROM manager_employee
LEFT JOIN manager_picture ON (manager_employee.empID = manager_picture.empID_id
AND manager_picture.isDef)

serializer.py

class PictureSerializer(serializers.ModelSerializer):
      class Meta:
            model = Picture
            fields = (
                  'empID',
                  'picture',
                  'isDef'
            )

class EmployeeListSerializer(serializers.ModelSerializer):
      pictures = PictureSerializer(many = True, read_only = True)

      class Meta:
            model = Employee
            fields = (
                  'empID',
                  'empLastname',
                  'empFirstname',
                  'empMiddlename',
                  'fullname',
                  'pictures'
            )

此查询给了我正确的结果..问题在于如何在Django中进行..

假设我有员工模型的记录

=============================================================================
empID    | empLastname    | empFirstname  | empMiddlename | fullname        |
=============================================================================
  1      | Doe            | John          | Smith         | Doe, John Smith |
-----------------------------------------------------------------------------
  2      | Potter         | Harry         | Moon          | Potter, Harry ..|
-----------------------------------------------------------------------------
  3      | Aaaa           | Abbb          | Accc          | ...             |
-----------------------------------------------------------------------------
  4      | Baaaa          | Bbbb          | Bccc          | ...             |
-----------------------------------------------------------------------------

现在在图片模型中

================================================
empID     | Picture                   | isDef  |
================================================
  1       | Pic1.jpg                  | 0      |
------------------------------------------------
  1       | Pic2.jpg                  | 0      |
------------------------------------------------
  1       | Pic3.jpg                  | 1      | *which makes this as default*
------------------------------------------------
  2       | emp2Pic1.jpg              | 1      | *which makes this as default*
------------------------------------------------
  2       | emp2Pic2.jpg              | 0      |
------------------------------------------------
  4       | emp4Pic1.jpg              | 0      |
------------------------------------------------
  4       | emp4Pic2.jpg              | 1      | *which makes this as default*
------------------------------------------------

现在当我尝试这个SQL时:

SELECT manager_employee.`*`, manager_picture.*
    FROM manager_employee
    LEFT JOIN manager_picture ON (manager_employee.empID = manager_picture.empID_id
    AND manager_picture.isDefault)

这给我一个结果:

=========================================================================
empID | empLastname | empFirstname | empMiddle | Picture      | isDef   |
 1    | Doe         | John         | Smith     | Pic2.jpg     | 1       |
 2    | Potter      | Harry        | Moon      | emp2Pic1.jpg | 1       |
 3    | Aaaa        | Abbb         | Accc      | (null)       | (null)  |
 4    | Baaaa       | Bbbb         | Bccc      | emp4Pic2.jpg | 1       |
-------------------------------------------------------------------------

如何在Django中实现它?

请有人帮帮我.. TIA ..

1 个答案:

答案 0 :(得分:0)

Django为您提供了ORM,因此您无需编写SQL。 检查一下:Django queryset API reference

此外,如果您想检查Django查询在SQL中的外观。你可以在django shell终端中尝试这样:

>>> queryset = MyModel.objects.all()
>>> print queryset.query
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"
相关问题