title: Generic relations vs. iterating on objects in Django
body: <p>I have three models called Post, Category and Flag.
  I let users to make a Flag on each Post which is tagged with a Category. Now I want to list all of Flags, related to Posts on a certain Category.
  I've found two ways of doing it using ListView generic view:</p>
  
  <p>First approach:<br>
  Define a generic relation between Flag and Category so I can call something like: <code>Flag.objects.filter(object__categor=self.category)</code></p>
  
  <p>Second approach:  </p>
  
  <pre><code>def get_queryset(self):
      pk = self.kwargs['pk']
      self.category = get_object_or_404(Category, pk=pk)
      flags = Flag.objects.all()
      qs=[]
      for f in flags:
          if f.object.category == self.category:
              qs.append(f)
      return qs
  </code></pre>
  
  <p>My question is which approach is more efficient? I'm not familiar with generic relations, but it seems a little bit heavy to do. On the other hand, querying on all Flag objects and iterating through them isn't cheap one.</p>
  
  <p>Models.py</p>
  
  <pre><code>class Flag(models.Model):
      flagger = models.ForeignKey(User, related_name='flaggers')
      content_type = models.ForeignKey(ContentType)
      object_id = models.PositiveIntegerField()
      object = GenericForeignKey('content_type', 'object_id')
      submit_date = models.DateTimeField(auto_now_add=True)
      reason  = models.IntegerField(choices=REASON_CHOICES, default=BROKEN_LINK)
  
  class Category(models.Model):
      name = models.CharField(max_length=100)
      slug = models.SlugField(unique=True)
      ...
  
  class Base(models.Model):
      title = models.CharField(max_length=200)
      slug = models.CharField(max_length=200, db_index=True)
      category = models.ForeignKey(Category, default=1)
      ... 
  class Text(Base):
      description = models.TextField(max_length=500)
      ...
  class Image(Base):
      image = models.ImageField()
  
  class Post(models.Model):
      content_type = models.ForeignKey(ContentType)
      object_id = models.PositiveIntegerField()
      content_object = GenericForeignKey('content_type', 'object_id')
      created_at = models.DateTimeField(null=True)
  </code></pre>
  
  <p>After saving each of Text or Image instances, I create a Post model. So I can get either Posts flagged or text flagged and image flagged separately.</p>
  
  <p>[also any tip about how can I define generic relation in case I should use it, would be appreciated]</p>