shyam rathod
shyam rathod

Reputation: 145

How to make many to many query set

Here My Branch table and Store Table

How many branch record available in store table and count. I'm try it but can't get it.

class Branch(models.Model): # Branch Master
    status_type = (
        ("a",'Active'),
        ("d",'Deactive'),
    )
    name = models.CharField(max_length=100, unique=True)
    suffix = models.CharField(max_length=8, unique=True)
    Remark = models.CharField(max_length=200, null=True, blank=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    create_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=1, choices = status_type, default = 'a')
    def __str__(self):
        return self.name

class Store(models.Model):
    status_type = (
        ("y",'Yes'),
        ("n","No")
    )
    branch = models.ManyToManyField(Branch)
    asset = models.ForeignKey(Asset,on_delete=models.CASCADE)
    asset_code = models.CharField(max_length=100, null=True, blank=True, unique = True)
    model = models.CharField(max_length=250)
    serial_no = models.CharField(max_length=200)
    vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE)
    invoice_no = models.CharField(max_length=50)
    purchase_date = models.DateField()
    store_status = models.CharField(max_length=1, choices = status_type, default = "y", blank = True)
    store_date = models.DateTimeField(null = True, blank = True)

    assige = models.CharField(max_length=1, choices = status_type, default = "n", blank = True)
    assige_date = models.DateTimeField(null = True, blank = True)
    
    scrap = models.CharField(max_length=1, choices = status_type, default = "n", blank = True)
    scrap_date = models.DateTimeField(null = True, blank = True)
    
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)
    create_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)

Query

get store object

store_obj = Store.objects.get( id= 5)

try to get count of branch record

tempcount = Store.objects.filter( branch = store_obj ).count()

I'm tired to get branch count.

Upvotes: 1

Views: 34

Answers (1)

blhsing
blhsing

Reputation: 106455

To get the count of branch records associated with a store, you should query the Branch model instead. Since reverse m2m queries are supported, you can simply do:

branch_count = Branch.objects.filter(store=store_obj).count()

Upvotes: 1

Related Questions