基于当前对象的多对多字段筛选对象

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

Filtering objects based on many-to-many field in current object

问题

如何在我的视图中基于当前饮料筛选drinkTagdrinkTagTaste?我尝试过:

similar_drinks = DrinkRecipe.objects.filter(drinkTag__drinkTag=obj.drinkTag)

但这不起作用。硬编码其中一个标签可以正常工作。任何帮助将不胜感激。

英文:

I have a drinks recipe app I'm building that has tags in a many-to-many field that are part of each drink. The tags are a basic taste description.
I now want to display 3 similar drinks based on the tag of the current drink.

My view looks like this:

def drinkdetail_view(request, slug=None):
    #Grab the correct drink
    try:
        obj = DrinkRecipe.objects.get(slug=slug)
    except:
        obj = None
    if obj is  None:
        return HttpResponse("Not found.")
   
context = {
    "drink": obj,
}

return render(request,'drinks/drinkdetail.html', context)

The model looks like this:

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

    def __str__(self):
        return f"{self.drinkTag}"

class TagTaste(models.Model):
    drinkTagTaste = models.CharField(max_length=255, blank=False)

    def __str__(self):
        return f"{self.drinkTagTaste}"
    
class Ingredient(models.Model):
    ingredientRum = models.ForeignKey('Bottle', on_delete=models.SET_NULL, null=True, blank=True)
    ingredientName = models.CharField(max_length=255, blank=True)
    ingredientAmount = models.DecimalField(decimal_places=1,max_digits=5)
    drink = models.ForeignKey('DrinkRecipe', on_delete=models.CASCADE)

    def __str__(self):
        if self.ingredientRum:
            return f"{self.ingredientRum}"
        else:
            return f"{self.ingredientName}"


class DrinkRecipe(models.Model):
    drinkTag = models.ManyToManyField(Tag)
    drinkTagRum = models.ForeignKey(Bottle, on_delete=models.SET_NULL, null=True)
    drinkTagTaste = models.ManyToManyField(TagTaste)
    drinkName = models.CharField(max_length=255, blank=False)
    drinkDescription = HTMLField()
    drinkImage = models.ImageField(upload_to=image_upload_handler)
    drinkActive = models.BooleanField(default=True)
    slug = models.SlugField(unique=True, blank=True, null=True)
    imgLocation = 'drinks'

    def __str__(self):
        return f"{self.drinkName}"


    def get_ingredients(self):
        return self.ingredient_set.all()
    
    def get_absolute_url(self):
        return reverse ('rhumSite:drinkDetail', kwargs={'slug':self.slug})

How do I filter for drinkTag or drinkTagTaste in my view based on the current drink?
I've tried:

similar_drinks = DrinkRecipe.objects.filter(drinkTag__drinkTag=obj.drinkTag)

But that doesnt work. Hardcoding one of the tags works just fine.
Any help would be much appreciated.

答案1

得分: 1

你可以使用以下方式筛选:

similar_drinks = DrinkRecipe.objects.filter(drinkTag__drinkrecipe=obj)

注意: 通常,Django 模型中的字段名采用 snake_case,而不是 PascalCase,因此应为:drink_tag 而不是 drinkTag

英文:

You can filter with:

<pre><code>similar_drinks = DrinkRecipe.objects.filter(<b>drinkTag__drinkrecipe=obj</b>)</code></pre>


> Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: drink_tag instead of <s>drinkTag</s>.

huangapple
  • 本文由 发表于 2023年4月11日 01:32:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979309.html
匿名

发表评论

匿名网友

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

确定