I’m currently trying to count user activity, but will only count it two days after they first sign up. Since I’m going to be postprocessing the data, I’d like to have it return a Django QuerySet.
The only fields that are relevant are the following:
User
user_id, install_time
Activity
user_id, date, [list of activities]
While I have hacked together a solution, it is extremely inefficient ( O(n²) ), since I have to match the user_ids individually in consecutive forloops.
As it stands, ForeignKey fields would not fit in my models. I found this; however, I can’t find a way that will only return a QuerySet where user_ids match and date > install_time + datetime.timedelta(2).
Any ideas?
EDIT: Here’s my models:
class User(models.Model):
user_id = models.CharField(max_length=36)
install_time = models.DateTimeField()
class Activity(models.Model):
user_id = models.CharField(max_length=36)
date = models.DateTimeField()
# Misc activity-related fields
As your models aren’t using explicit joins, you can’t use field
Fobjects as Chris Pratt suggested.If you are unable to modify your schema, I can see two other options that still leverage some of the django ORM, but require you to write SQL queries/fragments.
I’m assuming postgresql and completely guessing at the db schema that django might from your models that you’ve said aren’t correctly named.
QuerySet.extraE.g.:
Using
extracan be awkward, you can check the sql it’s producing bystr(activity_set.query).Alternatively, you could use the
Manager.rawand hand craft the query entirely. E.g.: