开发者

Filtering query with a foreign key

开发者 https://www.devze.com 2023-03-11 11:05 出处:网络
I have the following Models: class Categories(models.Model): name = models.CharField(max_length=200, unique=True)

I have the following Models:

class Categories(models.Model):
    name = models.CharField(max_length=200, unique=True)

class Funnies(models.Model):
    title = models.CharField(max_length=200)
    category = models.ForeignKey(Categories)

In a case where I have a variable holding a category name (myVar), instead of开发者_如何学编程 getting all rows in Funnies that hold a reference to the category the long way:

category_id = Categories.objects.get(name = myVar)
funnies_list = Funnies.objects.filter(category = category_id)

Is there a shorter, more "django" way of getting funnies_list ?

Meir


well if you have myVar already then

funnies_list = Funnies.objects.filter(category__name=myVar) 

would work.

0

精彩评论

暂无评论...
验证码 换一张
取 消