I’m using Django 1.3, and would like to get an array of objects using a ‘group by’ kind of query. Here’s some simplified code:
class Product(models.Model):
id = models.IntegerField(primary_key=True)
active = models.BooleanField()
name = models.CharField(blank=True, max_length=500)
slug = models.SlugField(blank=True, max_length=500)
program = models.CharField(blank=True, max_length=500)
number = models.CharField(blank=True, max_length=500)
image = ...
url = ...
in shell:
>>> p = Product.objects.all().some_group_functions('slug')
>>> p
[<Product: Abelly Hat>, <Product: Abelt Bracelet>, <Product: Abigail Earrings>, <Product: Abigail Earrings>'...(remaining elements truncated)...']
how to get only the objects with unique slug in my variable p?
Is there any way to get the Product objects as a list?
EDIT: possible workaround
Although it does what i want it to do, please let me know if you have any better solutions:
in my view, the logic gets an object QuerySet:
products = Product.objects.filter(*whatever filter you like*)
products = remove_duplicates(products, 'slug')
And the remove_duplicates function
def remove_duplicates(seq, attr=None):
seen = {}
result = []
for item in seq:
if attr:
tmpattr = getattr(item, attr)
else:
tmpattr = item
if tmpattr in seen: continue
seen[tmpattr] = 1
result.append(item)
return result
Since nobody answered anymore, I guess there’s no other simpler way than upgrading to django 1.4, which supports the functions distinct([fields]); django 1.3 only supports function distinct(), without parameters.
I tried upgrading, however django-cms untill today doesn’t support django 1.4. I’ll have to stick with the remove-duplicates function explained here 🙁