Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

python - Dynamic Queryset Based on Special Model Django

I would like to have a page that contains product and related competitor products with it. I tried, but all the times competitor products stay same. Would you please help me?

models:

class Product(models.Model):
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
category   = models.CharField(max_length=120)
brand      = models.CharField(max_length=120)
product    = models.CharField(max_length=120)
price      = models.DecimalField(decimal_places=2,max_digits=100)

class Comp_Product(models.Model):

product     = models.ForeignKey(Product,on_delete=models.CASCADE)
competitor  = models.URLField()
price       = models.DecimalField(decimal_places=2,max_digits=100)
change      = models.FloatField()
stock       = models.BooleanField()
last_update = models.DateField(auto_now_add=True)

views:

class ProductListView (ListView):
model = Comp_Product
context_object_name = 'comp_products'
template_name = 'products.html'

class ProductDetailView (LoginRequiredMixin,DetailView): 
model         = Product
template_name = 'product.html'

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['comp_products'] = Comp_Product.objects.all()
    return context

urls.py:

path('product/<int:pk>/', ProductDetailView.as_view(),name='product_detail'),
path('comp_products/', ProductListView.as_view(),name='comp_products'),
question from:https://stackoverflow.com/questions/66053481/dynamic-queryset-based-on-special-model-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here you say comp_products = All the Comp Products in the database.

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
>>> context['comp_products'] = Comp_Product.objects.all()
    return context

What do you display in your template? Is it {{comp_products}} or

{% for pr in product.comp_products.all %}
  {{ pr }}
{% endfor %}

For this you need related_name="products" in your product field in the Comp_Product model


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...