How to abstract a random data getter for Django?
i have a piece of code to get random data from database:
def get_random_item(model,queryset,id_column_name):
max_id = getattr(model.objects.order_by('-%s'%id_column_name)[0],id_column_name)
min_id = math.ceil((max_id-100000)*random.random()) + 100000
return queryset.filter(**content_id**__gte=min_id)[0]
as u can see,i want to abstract a function for any model,but i don't know how to replace the "content_id",cauz it's not a string or simply an attribute but开发者_开发技巧 with __gte.
tks for your answers~
"The pk lookup shortcut"
For convenience, Django provides a
pk
lookup shortcut, which stands for "primary key".
You can try queryset.filter(**{"%s__gte" % (column_name,): min_id)
You can read more about it here
精彩评论