Home > database >  How do i get all the objects which is in ManyToMany field in Django models
How do i get all the objects which is in ManyToMany field in Django models

Time:12-14

I have two models and in the second model, i created a ManyToMany field

class Listing(models.Model):
    title = models.CharField(max_length=50)
    name = models.CharField(max_length=100)
    description = models.TextField()
    starting_bid = models.IntegerField()
    category = models.CharField(max_length=50, blank=True)
    image = models.TextField(blank=True)
    posted_by = models.ForeignKey(User, on_delete=models.CASCADE)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.title
    

class Catagories(models.Model):
    category = models.CharField(max_length=100)
    listings = models.ManyToManyField(Listing, blank=True, related_name="cat")
 

Now let's assume i have created category "Electronics" and I have saved 3 listings in this category with the title "Mobile, laptop, microwave".

Now i want to get all the listings inside this category and I'm not getting it.

Now Questions is:

How do i get all of the listing items inside this category?

CodePudding user response:

You can filter with:

my_category.listings.all()

we thus have a Category named mycat and we can retrieve the Listings of that Category.

If you only have the category name, you can work with:

Listing.objects.filter(cat__category='my category name')
  • Related