Skip to content

Instantly share code, notes, and snippets.

@debuggerpk
Created January 5, 2017 23:20
Show Gist options
  • Select an option

  • Save debuggerpk/0bdd97b56a09c6d947ccfcda296fd867 to your computer and use it in GitHub Desktop.

Select an option

Save debuggerpk/0bdd97b56a09c6d947ccfcda296fd867 to your computer and use it in GitHub Desktop.
Unique for M2M fields
from django.db.models import QuerySet, Manager
class BaseRankManager(Manager):
def rank(self, field_name, user_id, **kwargs):
"""
Gets unique items from the datebase based on the foreign key. this
queryset is ordered in reverse chronological order.
Args:
field_name (str): name of the foreign key field
user_id (int): user upon which the result is to be filtered.
**kwargs (dict): extra keyword which match column enteries if needed
Returns:
name (object): RawQuerySet, limited in its functionality, but can be
iterated over.
"""
db_name = self.model._meta.db_table
query = """
SELECT * FROM (
SELECT *,
rank() OVER (
PARTITION BY {field_name}_id
ORDER BY added_on DESC
) FROM {db_name}
) videosrank
""".format(field_name=field_name, db_name=db_name)
ordering = ' ORDER BY added_on DESC;'
where_stmnt = 'WHERE rank = 1 AND user_id = {user_id}'.format(
user_id=user_id
)
if len(kwargs):
for k, v in kwargs.iteritems():
# v = "1" if v == True else "0"
where_stmnt += ' AND {k} = {v}'.format(k=k, v=v)
query += where_stmnt
query += ordering
return self.raw(query)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment