How do I return a queryset of all items (X) ManyToMany related to model class (Y) and include values for (Y) in the same result in each item X

20 views
Skip to first unread message

mtp...@gmail.com

unread,
Jul 5, 2021, 3:28:35 AM7/5/21
to Django users
I have the following two model classes:

```
class Property(models.Model):
    """Represents property class model"""
    serial_no = models.CharField(unique=True,max_length=255,blank=True,null=True)
    map_no = models.CharField(max_length=255,blank=True,null=True)
    lr_no =  models.CharField(max_length=255,blank=True,null=True)
    locality =  models.CharField(max_length=255,blank=True,null=True)
```

```
class PropertyObjection(models.Model):
    """Represents property objection class. This has properties that have been objected"""
    objector_name = models.CharField(max_length=255,null=True, blank=True)
    objection_no = models.CharField(max_length=255,null=True, blank=True)
    properties =  models.ManyToManyField(Property,blank=True)
    ratable_owner = models.BooleanField(null=True,blank=True)
    ratable_relation = models.CharField(max_length=50,null=True, blank=True)
```
Which is the most effective way to get all properties that have been objected using the `PropertyObjection` class. One other thing to note is that each property should have values for `objection_no`, `ratable_owner` and `ratable_relation` values. 

The expected result should look something like this:
```
[
    {
    'objector_name': "Angela Rudolf",
    'serial_no': "5603883",
    'map_no': "238",
    'lr_no': "234/R",
    'locality': "Nairobi",
    'objection_no': "pv876646",
    'ratable_owner': True,
    'ratable_relation': "N/A"
   }
]
```

I attempted this implementation but its not the most effective way to do so considering when data eventually grows (I tried this when I have more than 5000 records and the request takes long to return a response. I'd like to use the ORM methods to effectively populate the required queryset.


```
class ObjectUsvAPIView(generics.ListAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    queryset = PropertyObjection.objects.all()
    pagination_class = PageNumberPagination


    def get_queryset(self):
        """
        This view should return a list of all the properties objected.
        """

        
        qs = PropertyObjection.objects.prefetch_related('properties')


        poplulated_list = (
            {   
                "id":item.id
                "property": property,
                "ratable_owner": item.ratable_owner,
                "ratable_relation":  item.ratable_relation,
                "objector_name": item.objector_name

                }
            
            
            for item in qs   for property in item.properties.all()
                

        )
   

        return list(poplulated_list)
```
Reply all
Reply to author
Forward
0 new messages