Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How can I select objects with the same field values?

For example, I have a model like this:

Class Doggy(models.Model):
    name = models.CharField(u'Name', max_length = 40)
    color = models.CharField(u'Color', max_length = 20)

How can i select doggies with the same color? Or with the same name :)

UPD. Of course, I don't know the name or the color. I want to.. kind of, group by their values.

UPD2. I'm trying to do something like that, but using Django:

SELECT * 
FROM table 
WHERE tablefield IN ( 
 SELECT tablefield
 FROM table 
 GROUP BY tablefield  
 HAVING (COUNT(tablefield ) > 1) 
) 

UPD3. I'd like to do it via Django ORM, without having to iterate over the objects. I just want to get rows with duplicate values for one particular field.

like image 725
DataGreed Avatar asked Oct 29 '25 10:10

DataGreed


1 Answers

I'm late to the party, but here you go:

Doggy.objects.values('color', 'name').annotate(Count('pk'))

This will give you results that have a count of how many of each Doggy you have grouped by color and name.

like image 61
Brad Martsberger Avatar answered Oct 31 '25 02:10

Brad Martsberger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!