How to filter only defined number of items in ManyToMany field?

Hello,
I have an app with Restaurant model which has type_of_food(ManyToMany field) here is the model:

class Restaurants(models.Model):
    name = models.CharField(max_length=30, unique=True)
    slug = models.SlugField(max_length=30, unique=True)
    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    address = models.CharField(max_length=150)
    website = models.CharField(max_length=100, blank=True, null=True)
    email = models.EmailField()
    phone = models.CharField(max_length=13)
    type_of_food = models.ManyToManyField(TypeOfFood, blank=True)
    available = models.BooleanField(default=False)
    description = models.TextField(blank=True, max_length=1000)
    logo = models.ImageField(upload_to='Restaurant_Logos')
    date_added = models.DateTimeField(auto_now_add=True)

So in the Template I want to show only 3 out of many type_of_foods that restaurants have.
I tried to do this in the template:

{% for type in restaurant.type_of_food.all[:2] %}{{ type }}{% endfor %}

But Django template seems to not work with .
In the template im looping through all the Restaurants, so I can’t make a new object in the views for type_of_food seperatly and restrict it to only [:2].
I’m gonna be really gratefull if someone help me!
Thank you!

mmm not sure but you could try something like this?

class Restaurants(models.Model):
    <snip>

    @property
    def type_of_food_first_three(self):
        return self.type_of_food.all()[:2]

and in the view, to avoid the extra queries, use prefetch_related:

restaurants = Restaurants.objects.filter(...).prefetch_related(
    'type_of_food'
)

and in the template:

{% for type in restaurant.type_of_food_first_three %}
    {{ type }}
{% endfor %}

Haven’t tried to run this, but hopefully that helps you try things in the right direction!

1 Like

It worked, thank you very much!

There might be a better approach with Prefetch() (which offers more fine-tuned control over prefetch) but hey – look it up :slight_smile:

1 Like