Home > database >  Get ManytoMany Objects in Django
Get ManytoMany Objects in Django

Time:03-26

I am trying to solve an issue. Like I have two model service and package. package has relation with service in many to many. I want to get the service's name which are not having any many to many relation with the package table. How to do this? I have tried multiple apporch.

#models.py

class Service(models.Model):
    name = models.CharField(max_length=1000)
    price = models.IntegerField(null=True, blank=True, default=0)
    details = models.TextField(max_length=20000, blank=True, null=True)
    status = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name


class Package(models.Model):
    service = models.ManyToManyField(Service, blank=True)
    name = models.CharField(max_length=220)
    price = models.IntegerField(null=True, blank=True, default=0)
    details = models.TextField(max_length=20000, blank=True, null=True)
    status = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

#views.py

    children_id_list = [2, 1, 4]
    temp = []
    
    for i in children_id_list:
        try:
            s = Service.objects.get(id=i)
            t = s.package_set.all()
            if len(t) == 0:
                children_id_list.remove(i)
                temp.append(i)
        except ObjectDoesNotExist:
            print(f'Sorry! There is no Service List with this ID {i}')


    print(children_id_list)
    print(temp)
    print(f"\n")
    package = Package.objects.filter(service__in=children_id_list).annotate(num_cats=Count('service')).filter(num_cats=len(children_id_list)).exclude(service__in=Service.objects.exclude(id__in=children_id_list))

    for i in package:
        print(f"Hello, Package Name {i.name} and Price {i.price} BDT")
        if len(temp) > 0:
            c = Service.objects.get(id=temp[0])
            print(f"Addon for new service {c.price} BDT")
            u = i.price   c.price
            print(f"Total Checkout {u} BDT")
            print(f"\n")
        else:
            print('None')

CodePudding user response:

  1. If you want to fetch service name then you can use
variable_name =  Service.objects.get(name = service_name)
  1. If you want to fetch service name using Package model.
variable_name =  Package.objects.get(service__name = service_name)

CodePudding user response:

add related name to your Package model like this:

class Package(models.Model):
    service = models.ManyToManyField(Service, blank=True, related_name="packages")

Then try this:

Service.objects.filter(packages__is_null=True)
  • Related