Search code examples
djangodjango-haystackwhoosh

Index related table using Haystack/Whoosh


How can I index a related table:

class Foo(models.Model):
   name = models.CharField(max_length=50)

Class FooImg(models.Model):
   image = models.ImageField(upload_to='img/', default = 'img/no-img.jpg',
                              verbose_name='Image', )
   foo = models.ForeignKey(Foo, default=None, null=True, blank=True)

I want to index FooImg, so that I can get the images associated with Foo.

I have already indexed Foo, and it works perfectly fine, it returns expected result. So in my template I have:

{% for r in foo_search %}
   {{ r.object.name | slice:":18" }}
{% endfor %}

The above works, but I can't figure out how I can get the associated FooImg objects?

Looking for direction,


Solution

  • Add related_name to your fk:

    foo = models.ForeignKey(Foo, default=None, null=True, blank=True, related_name='images')
    

    Then get the images and do what you need with them, probably loop over them:

    obj.images.all()