简体   繁体   中英

How to filter a query by an instance in django rest framework?

I want to filter all comment objects using the property instance that name is "example". Basically I want to get all comments, which item name is "example". How can I do this filtering?

 class Comment(models.Model):
     item = models.ForeignKey(Item, on_delete=models.CASCADE)
     owner = models.ForeignKey(Account, on_delete=models.CASCADE)
     message_body = models.TextField()
     is_read = models.BooleanField(default=False)
     created_at = models.DateTimeField(auto_now_add=True)


 class Item(models.Model):
     category = models.ForeignKey(ItemCategory, on_delete=models.PROTECT)
     owner = models.ForeignKey(Account, on_delete=models.PROTECT)

     name = models.CharField(max_length=150)
     description = models.CharField(max_length=1000)
     address = models.CharField(max_length=150, null=True)

Thank you for your help!

Comment.objects.filter(item__name='example')

请参阅有关此主题的Django文档: https : //docs.djangoproject.com/en/1.11/ref/models/querysets/

comments = Comment.objects.filter(item__name='example')

In the views.py , you can get the result like this.

Syntax: Modelname.objects.filter(fieldname='value')

Comment.objects.filter(item__name='example')
Comment.objects.filter(item__name__iexact = 'example')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM