Django不在其他表中(不使用id)

时间:2016-12-11 14:04:58

标签: django django-queryset

我有:

型号:

class Category(models.Model):
    description = models.CharField(unique=True, max_length=200)                        
    myfield = models.CharField(unique=True, max_length=200)                        

class Car(models.Model):
    categorys = models.ManyToManyField(Category)   
    myfield = models.CharField(unique=True, max_length=200)                        

我正在尝试执行以下查询:

Car.objects.filter(category__id = c.id )
           .exclude(myfield__in =                      
                    Category.objects.all()
                            .only('myfield')
                    )
           .order_by("id")
           .first()

我希望找到这样的结果:

SELECT ...
 FROM `myapp_car` 
 INNER JOIN `myapp_car_categorys` 
        ON (`myapp_car`.`id` = `myapp_car_categorys`.`car_id`)    
WHERE ( ...
  AND NOT (`myapp_car`.`myfield` IN 
           (SELECT `myapp_category`.`myfield` FROM `myapp_category`))) 
ORDER BY `myapp_car`.`id` ASC LIMIT 1;

但我发现:

SELECT ...
 FROM `myapp_car` 
 INNER JOIN `myapp_car_categorys` 
        ON (`myapp_car`.`id` = `myapp_car_categorys`.`car_id`)    
WHERE ( ...
  AND NOT (`myapp_car`.`myfield` IN 
           (SELECT `myapp_category`.`id` FROM `myapp_category`))) 
ORDER BY `myapp_car`.`id` ASC LIMIT 1;

我需要在select中使用myfield,而不是id

(SELECT `myapp_category`.`myfield` FROM `myapp_category`)

我如何得到这个结果?

1 个答案:

答案 0 :(得分:1)

即使您使用only,它也会返回Category模型的对象。因此,如果您在过滤中使用它,则类别对象将用于过滤,而SQL则用于这些类别对象的ID。

如果您需要过滤所有类别对象的myfield值,请改用values

....exclude(myfield__in=Category.objects.values('myfield'))