Reputation: 442
I have:
Models:
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)
I am trying to execute the following query:
Car.objects.filter(category__id = c.id )
.exclude(myfield__in =
Category.objects.all()
.only('myfield')
)
.order_by("id")
.first()
I expected to find a result like this:
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;
But i find:
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;
I need use myfield
in select, not id
:
(SELECT `myapp_category`.`myfield` FROM `myapp_category`)
How would I get this result?
Upvotes: 0
Views: 953
Reputation: 19861
Even if you use only
it will return the objects of Category
model. So if you use it in in filtering the category objects will be used for filtering and for SQL the ids of those category objects.
If you need to filter on the myfield
values on all the category objects, then use values
instead:
....exclude(myfield__in=Category.objects.values('myfield'))
Upvotes: 1