Sampling with joins using Django models
I have a method in one of my models that right now fetches every link, and then does a random sample. Is it possible to make some form of join combined with a random selection using Django models? The current method seems like a great way to waste grind the application to a halt when the data grows. :)
class Link(models.Model):
link = models.URLField()
in_list = models.ForeignKey( 'linkrotator.LinkList',
related_name = 'links' )
class LinkList(models.Model):
in_list = models.ForeignKey('linkrotator.LinkListList',
blank = True,
null = True,
on_delete=models.SET_NULL,
related_name = 'lists')
class LinkListList(models.Model):
number_of_links = models.IntegerField()
def get_links(self):
links = []
for list in self.lists.all():
links.extend( list.links.all() )
if len( links ) <开发者_C百科;= self.number_of_links:
return links
return random.sample( links, self.number_of_links )
You can get a bunch of random links like this:
links = self.lists.all().order_by('?')[self.number_of_links]
But... that doesn't filter on the lists you want. You might be able to do something like this to get that: filter(list_set__id__in=...)
I thinks it's useful for Getting a random row from a relational database
精彩评论