Hesam Aghajani
Hesam Aghajani

Reputation: 73

How filter a model by model in Django

I'm having some trouble in filtering objects from a set of models.

I have 3 classes:

class Product(models.Model):
   id = models.UUIDField(default=uuid4, primary_key=True, editable=False)
   title_fa = models.CharField(max_length=80)
   title_en = models.CharField(max_length=80)
   ...

class Favorite(models.Model):
   user = models.ForeignKey(Profile, default=None, on_delete=models.CASCADE)
   product = models.ForeignKey('seller.Product', default=None, on_delete=models.CASCADE)
   ...

class Profile(models.Model):
   id = models.UUIDField(default=uuid4, primary_key=True, editable=False)
   first_name = models.CharField(max_length=80, blank=True, null=True)
   last_name = models.CharField(max_length=80, blank=True, null=True)
   shop_name = models.CharField(max_length=80, blank=True, null=True)
   ...

I trying to filter some thing like this:

favorite_product = Product.objects.filter(id=favorite__.id)

this is my view functions:

def profile(request):
    id = request.COOKIES['id']
    order__ = Order.objects.filter(sender=id)
    profile__ = Profile.objects.get(id=id)
    favorite__ = Favorite.objects.filter(user=id)
    favorite_product = Product.objects.filter(id=favorite__.id)

    return render(request, 'shop/profile/profile.html',
                  {'order': order__, 'profile': profile__, 'favorite_product': favorite_product})

I want to show that product which they id is in Favorite model by user = id .

template code :

{% for item in favorite_product %}
    <div class="profile-recent-fav">
        <a href="#"><img src="{{ item.image.url }}"></a>
        <div class="profile-recent-fav-col">
            <a href="#"></a>
            <div class="profile-recent-fav-price">{{ item.fa_name }}</div>
            <div class="profile-recent-fav-remove">
                <a href="#">
                    <i class="fa fa-trash"></i>
                </a>
            </div>
        </div>
    </div>
{% endfor %}

Upvotes: 4

Views: 75

Answers (3)

Tarun Kumar
Tarun Kumar

Reputation: 374

Try this-

favorite__ is queryset so you have to get the list of all product ids, you can do that like this

fab_product_ids=favorite__.values_list("product__id", flat=True)

Then you can filter the product like this

favorite_product = Product.objects.filter(id__in=fab_product_ids)

Hope this will help. There are other ways also to do the same thing

Upvotes: 1

root
root

Reputation: 192

You can have a look at the django documentation. It is very useful! https://docs.djangoproject.com/en/3.1/topics/db/queries/

Upvotes: 1

IliasMh
IliasMh

Reputation: 58

Try :

favorite_product = Product.objects.filter(id=favorite__.Product.id)

Comment If it is working.

Upvotes: 1

Related Questions