I'm trying to show a single instance (db row) from a model where several instances share the same field (column) value for several rows. To clarify that statement,I have the following situation:
ID/Title/Slug/Modified
1 Car A 1s ago
2 Car A 2s ago
3 House B 1s ago
If the above small table were my db I want my Django admin page to show distinct rows based on my slug field (column) show the last edited version (I have another column for time... So the above table would show up in the admin page as follows:
ID/Title/Slug/Modified
1 Car A 1s ago
3 House B 1s ago
Although row 1 & 2 have different pk's they have the same slug, I want only one of them with the later time...
I can achieve this in my views.py as follows
existing_data = MyModel.objects.filter(slug=slug).latest('modified')
but that's because I'm looking for a specific instance of a slug.. If I wasn't I could also use group_by...
I'm trying to get this display in admin page. I've tried the following techniques in a model manager,
class ModelManager(models.Manager):
def get_query_set(self):
return super(ModelManager, self).get_query_set().group_by('title')
but I get this error
'QuerySet' object has no attribute 'group_by'
Then I was reading this part of the Django book and they implemented raw sql in a model manager which I tried copying to my situation as follows,
class ModelManager(models.Manager):
def uniques(self):
cursor = connection.cursor()
cursor.execute("""
SELECT *
FROM eventform_event
GROUP BY slug
""")
return [row[0] for row in cursor.fetchone()]
Im my model I have
objects = ModelManager()
I'm just not sure how to get the admin model to view my custom manager that doesn't override the get_query_set. When I did use this custom manager to override the get_query_set I get this error
'long' object has no attribute '__getitem__'
I've also tried testing 'values(), values_list(), distinct() etc but they all give me errors... distinct() tells me my database (mysql) doesn't not support this feature.. now sure if I have to switch databases to achieve this feature and now I'm out of ideas to experiment with... Anybody know how to achieve this functionality.. Thanks.
#In my admin.py page I can get side filter (list_filter) to show unique entries based on the slug column per this thread recommendation...
Unfortunately I can't get the rows displayed in the admin page for my model to be unique based on a certain column...