根据另一个视图中的字符串来筛选对象。

huangapple go评论53阅读模式
英文:

How to filter an object based on string from another view

问题

以下是您要翻译的代码部分:

I'm displaying a list of drinks in a template. The drinks model has a many-to-many field with tags that group drinks together. I now want to filter the list of drinks based on this tag.
I've made the tag model like this:

    class Tag(models.Model):
        drink_tag = models.CharField(max_length=255, blank=False)
    
        def __str__(self):
            return f"{self.drink_tag}"
        
        def get_tag_link(self):
            return reverse('rhumSite:drinkDetailTag',kwargs={'tag':self.drink_tag})

This way, each tag has a link to a page that will display all the drins with said tag.
In my URLS.py file the path looks like this:

    path('cocktails/<str:tag>/',DrinksFilteredListView.as_view(template_name='rhumSite/drinks.html'),name='drinkDetailTag'),

When I click on a tag the url is indeed `cocktails/tagname` so that works well.
I now want my listview to take that tag and display all drinks from the drinks model with this tag. 

My view looks like this:

    class DrinksFilteredListView(ListView):
        model = DrinkRecipe
        context_object_name = 'drinks'
    
        def get_queryset(self):
            return DrinkRecipe.objects.filter(drink_tag__drinkrecipe=self.kwargs['tag'])
        
        def get_context_data(self, **kwargs):
            context= super().get_context_data(**kwargs)
            context['tags'] = Tag.objects.all()
            context['tastes'] = TagTaste.objects.all()
            context['bottles'] = Bottle.objects.all()
            return context

I know I have to use `get_queryset(self):` but I still struggle with getting the query right. Right now I get the error:

    Field 'id' expected a number but got 'Summer'.

where Summer is indeed the name of the tag.
Any help or insight would be much appreciated.

希望这有助于您的问题。

英文:

I'm displaying a list of drinks in a template. The drinks model has a many-to-many field with tags that group drinks together. I now want to filter the list of drinks based on this tag.
I've made the tag model like this:

class Tag(models.Model):
    drink_tag = models.CharField(max_length=255, blank=False)

    def __str__(self):
        return f&quot;{self.drink_tag}&quot;
    
    def get_tag_link(self):
        return reverse(&#39;rhumSite:drinkDetailTag&#39;,kwargs={&#39;tag&#39;:self.drink_tag})

This way, each tag has a link to a page that will display all the drins with said tag.
In my URLS.py file the path looks like this:

path(&#39;cocktails/&lt;str:tag&gt;/&#39;,DrinksFilteredListView.as_view(template_name=&#39;rhumSite/drinks.html&#39;),name=&#39;drinkDetailTag&#39;),

When I click on a tag the url is indeed cocktails/tagname so that works well.
I now want my listview to take that tag and display all drinks from the drinks model with this tag.

My view looks like this:

class DrinksFilteredListView(ListView):
    model = DrinkRecipe
    context_object_name = &#39;drinks&#39;


    def get_queryset(self):
        return DrinkRecipe.objects.filter(drink_tag__drinkrecipe=self.kwargs[&#39;tag&#39;])
    
    def get_context_data(self, **kwargs):
        context= super().get_context_data(**kwargs)
        context[&#39;tags&#39;] = Tag.objects.all()
        context[&#39;tastes&#39;] = TagTaste.objects.all()
        context[&#39;bottles&#39;] = Bottle.objects.all()
        return context

I know I have to use get_queryset(self): but I still struggle with getting the query right. Right now I get the error:

Field &#39;id&#39; expected a number but got &#39;Summer&#39;.

where Summer is indeed the name of the tag.
Any help or insight would be much appreciated.

Edit:
The drinks model looks like this:

class DrinkRecipe(models.Model):
    drink_tag = models.ManyToManyField(Tag)
    drink_tag_rum = models.ForeignKey(Bottle, on_delete=models.SET_NULL, null=True)
    drink_tag_taste = models.ManyToManyField(TagTaste)
    drink_name = models.CharField(max_length=255, blank=False)
    drink_description = HTMLField()
    drink_method = HTMLField()
    drink_garnish = HTMLField()
    drink_image = models.ImageField(upload_to=image_upload_handler)
    drink_active = models.BooleanField(default=True)
    slug = models.SlugField(unique=True, blank=True, null=True)

答案1

得分: 1

DrinkRecipe.objects.filter(drink_tag__drinkrecipe=self.kwargs['tag'] 正在检查标签的主键(如果我理解正确)

我认为你想要 DrinkRecipe.objects.filter(drink_tag__drink_tag=self.kwargs['tag']) 假设 self.kwargs['tag'] 是 Tag 模型实例中 CharField 的值。

DrinkRecipeTag 中重复使用字段名会让人感到困惑。如果在 Tag 中的字段被称为 name,那会更好。然后你可以像这样编写代码 tag.name='foo'.filter(drink_tag__name='foo')

英文:

DrinkRecipe.objects.filter(drink_tag__drinkrecipe=self.kwargs[&#39;tag&#39;] is checking on tag primary keys (if I understand it right)

I think you want DrinkRecipe.objects.filter(drink_tag__drink_tag = self.kwargs[&#39;tag&#39;] ) assuming self.kwargs[&#39;tag&#39;] is the value of the CharField in a Tag model instance.

The duplication of a field name in DrinkRecipe and Tag is confusing. It would be better if the field in Tag were called name. Then you would have code like tag.name=&#39;foo&#39; and .filter( drink_tag__name = &#39;foo&#39;)

huangapple
  • 本文由 发表于 2023年4月13日 18:33:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定