0

I have this model of

products

class Product(models.Model):
    name = models.CharField(max_length=50)
    productId = models.AutoField(max_length=50,primary_key=True)
    productType = models.CharField(max_length=50)
    productPrice = models.PositiveIntegerField(default=0)
    matType = models.CharField(max_length=100,default='Use comma , to seperate multiple materials Ex. Cotton 90%, Spandex 10%') #Multiple Material divided by comma,mat1 is main material
    seller = models.ForeignKey(User, related_name='sellers',on_delete=models.CASCADE,default='NA')
    cat_1 = models.ForeignKey(Cat1,related_name='catlevel1',on_delete=models.CASCADE,default='NA')

I have two foreign Keys, one is to User Class for seller information and another is to Categories with Model Name Cat1. For Same I have related names catlevel1 and sellers. I am using this code in HTML to access products by currently logged in user.


{% for prod in user.sellers.all %}

        {% for color in prod.colors.all %}
         {% for size in prod.sizes.all %}
        <tr>
          <td>{{ prod.name }}</td>
          <td>{{ prod.productPrice }}</td>
          <td>{{ prod.matType }}</td>
          <td>{{ color.colorMain }},{{ color.colorTrim }}</td>
          <td>{{ size.nameSize }}</td>
          <td>{{ size.quantity }}</td>
        </tr>
        {% endfor %}
      {% endfor %}
    {% endfor %}

The first loop (first line):

{% for prod in user.sellers.all %}

accesses all the products by current_user user. Here sellers is the related name of foreign key seller

I want to get data using both foreign keys,seller in User Class and categories under cat1.

So the main aim is to get products that are of the current user and current category. I have searched the internet but couldn't find any solution. Many of the solutions date back to Django 1.3 days and are not working now.

Some Suggested using select_related but I couldn't figure out how to use it here.

UPDATE: Models in Use:

class Cat1(models.Model):
    name = models.CharField(max_length=30)
    description = models.CharField(max_length = 100)

    def __str__(self):
        return self.name



class Product(models.Model):
    name = models.CharField(max_length=50)
    productId = models.AutoField(max_length=50,primary_key=True)
    productType = models.CharField(max_length=50)
    productPrice = models.PositiveIntegerField(default=0)
    matType = models.CharField(max_length=100,default='Use comma , to seperate multiple materials Ex. Cotton 90%, Spandex 10%') #Multiple Material divided by comma,mat1 is main material
    seller = models.ForeignKey(User, related_name='sellers',on_delete=models.CASCADE,default='NA')
    cat_1 = models.ForeignKey(Cat1,related_name='catlevel1',on_delete=models.CASCADE,default='NA')

View Used :

def cat_products(request,pk):
   categories = get_object_or_404(Cat1, pk=pk)
   colors = Color.objects.all()
   products = Product.objects.all()
   sizes = Size.objects.all()
   sellerproducts = user.sellers.select_related('cat_1')filter(cat_1__categories=category)
   user = request.user
   return render(request, 'products.html', {'categories':categories,'products':products,'colors':colors,'sizes':sizes,'user':user,'sellerproducts':sellerproducts})

This is how i am using : user.sellers.select_related('cat_1')filter(cat_1__categories=category) I know that i have to tweak the names of the variables but the error is invalid syntax.

Dushyant Deshwal
  • 388
  • 4
  • 17

2 Answers2

1

Your template should actually render the response. The way you did in your answer is not feasible. You are just hiding the extra results. Instead, you should query for the results which are needed.

you can do user.sellers.select_related('cat_1').filter(cat_1__categories=category) and pass the result to your template. But you need to execute this query in the view. That's because it'll give you more control and if you want to implement any pagination or any extra feature it'll be easy to do that.

  • I will try this.I could find out how to get select_related word. Will get back to you ! – Dushyant Deshwal Jul 03 '19 at 10:09
  • https://stackoverflow.com/users/9917871/dharanidhar-reddy I couldn't get it to work.I am very new to django. I updated the question with models.If you could help how i should be using. It gives an error of invalid syntax. – Dushyant Deshwal Jul 09 '19 at 04:05
  • you have to use the code only after getting into the scope of the `user`. move the code after `user = request.user` line. After this user will be available. Then the query will be executed. – Dharanidhar Reddy Jul 09 '19 at 04:27
  • Since you are already getting a Category object, It should be `user.sellers.select_related('cat_1').filter(cat_1=category)`. – Dharanidhar Reddy Jul 09 '19 at 04:31
  • Also i used `.filter(cat_1=categories)` the object of `cat_1` i already have. Thanks for all the help. Now i have the perfect way to do this sorting procedure. – Dushyant Deshwal Jul 09 '19 at 04:40
0

Follow the answer to this question> That is the correct way.

{% for prod in user.sellers.all %}
       {% if prod.cat_1.name == categories.name %}
         {% for color in prod.colors.all %}
         {% for size in prod.sizes.all %}
          <tr>
            <td>{{ prod.name }}</td>
            <td>{{ prod.productPrice }}</td>
            <td>{{ prod.matType }}</td>
            <td>{{ color.colorMain }},{{ color.colorTrim }}</td>
            <td>{{ size.nameSize }}</td>
            <td>{{ size.quantity }}</td>
          </tr> 
          {% endfor %}
         {% endfor %}
      {% endif %}
    {% endfor %}

I used this code to segregate the data. Using if block to check if the product that has been selected by the current_user filter loop used in first line have the same category name as the current selected category.

Here categories hold current category and prod hold the selected product.

{% if prod.cat_1.name == categories.name %} Above line checks for the name. and then prints the information inside if. {%endif%} if used to end the if tag.

Dushyant Deshwal
  • 388
  • 4
  • 17