kishore
kishore

Reputation: 413

Get similar objects of same type from django taggit

I am using django-taggit tags in two models, lets say Model1 and Model2. I am using below code to get similar objects from my one of the model.

obj1 = Model1.objects.get(pk=1)
similar = obj1.tags.similar_objects()

In the similar objects I am getting Model2 objects also. So How to get only Model1 similar objects.

Upvotes: 5

Views: 362

Answers (1)

darl1ne
darl1ne

Reputation: 416

By default django-taggit uses a “through model” with a GenericForeignKey on it, that has another ForeignKey to an included Tag model. However, there are some cases where this isn’t desirable, for example if you want the speed and referential guarantees of a real ForeignKey, if you have a model with a non-integer primary key, or if you want to store additional data about a tag, such as whether it is official. In these cases django-taggit makes it easy to substitute your own through model, or Tag model. see docs

Suppose we have a Food model.Сreate a through model, in the same place as your Model

models.py

from django.db import models

from taggit.managers import TaggableManager
from taggit.models import TaggedItemBase


class TaggedFood(TaggedItemBase):
    content_object = models.ForeignKey('Food', on_delete=models.CASCADE)

class Food(models.Model):
    # ... fields here

    tags = TaggableManager(through=TaggedFood)

views.py

from django.shortcuts import get_object_or_404, render
from .models import Food

def food(request, pk):
    food = get_object_or_404(Food, pk=pk)
    similar_foods = food.tags.similar_objects()[:5]
    context = {
        'food':food,
        'similar_foods':similar_foods
    return render(request, 'food.html', context)

food.html

{{ food.field }}
{% for food in similar_foods %}
    {{ food.field }}
{% endfor %}

So the queryset will be executed only on the Food model. Do the same for the other model if necessary.

Upvotes: 2

Related Questions