DjangoのManytoManyFieldを検索したい
解決したいこと
Djangoのmodels.pyに登録しているProduct内のtagsというManytoManyFieldのモデルを検索したいです。
models.py
from django.db import models
from django.urls import reverse
from django.shortcuts import render
class PostTag(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(verbose_name='商品名', max_length=250, unique=True)
slug = models.SlugField(verbose_name='URLに表示される名前', max_length=250, unique=True)
description = models.TextField(verbose_name='説明', blank=True)
# tag = models.ManyToManyField(Tag)
price = models.IntegerField()
image = models.ImageField(upload_to='product', blank=True)
product_name = models.CharField(max_length=255, null=True)
hover_image = models.ImageField(verbose_name='ポップアップの画像', upload_to='producthover', blank=True, )
product_name2 = models.CharField(max_length=255, null=True)
hover_image2 = models.ImageField(verbose_name='ポップアップの画像2', upload_to='producthover2', blank=True, )
product_name3 = models.CharField(max_length=255, null=True)
hover_image3 = models.ImageField(verbose_name='ポップアップの画像3', upload_to='producthover3', blank=True, )
product_name4 = models.CharField(max_length=255, null=True)
hover_image4 = models.ImageField(verbose_name='ポップアップの画像4', upload_to='producthover4', blank=True, )
stock = models.IntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(PostTag)
file = models.FileField(upload_to='file', blank=True)
objects = models.Manager()
valid_objects = ValidManager()
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def __str__(self):
return '{}'.format(self.name)
def get_url(self):
return reverse('shop:product_detail', args=[self.slug])
def index(request):
image_request = request.user.set_image_path
return render(request, 'shop/base.html', {'image_request': image_request})
views.py
from django.shortcuts import render
from shop.models import Product
from django.db.models import Q
def search_result(request):
products = None
query = None
if 'q' in request.GET:
query = request.GET.get('q')
products = Product.objects.all().filter(Q(name__contains=query) | Q(description__contains=query))
return render(request, 'search.html', {'query': query, 'products': products})
0