tuomur / python-odata

A simple library for read/write access to OData services
MIT License
79 stars 59 forks source link

Using select should not return JSON #32

Open tpow opened 5 years ago

tpow commented 5 years ago

I'm possibly missing something, but it seems like a query using select should return entities just like the same query without the select. (Obviously not all properties will be populated, but that's kind of the point of a select). Here's the Demo example:

from odata import ODataService
url = 'http://services.odata.org/V4/Northwind/Northwind.svc/'
Service = ODataService(url, reflect_entities=True)
Supplier = Service.entities['Supplier']

query = Service.query(Supplier)
query = query.limit(2)
query = query.order_by(Supplier.CompanyName.asc())

for supplier in query:
    print('Company:', supplier.CompanyName)

This works fine and prints the CompanyNames of the suppliers. However, if you add query = query.select(Supplier.CompanyName)

Then you also need to change the print statement like this: print('Company:', supplier['CompanyName'])

The syntax change is unexpected and switching from the object to JSON dict is strange. It'd be nice if the query would return the entities with only the selected properties populated so the code doesn't need to change. In fact, it looks like the entity already supports this using from_data.

I commented out part of the _create_model method in query.py and it seems to work fine --- the entity is returned when using the select and the other properties are left as None.

    def _create_model(self, row):
        #if len(self.options.get('$select', [])):                                                       
        #    return row
        #else:
            e = self.entity.__new__(self.entity, from_data=row)
            es = e.__odata__
            es.connection = self.connection
            return e

Is there some reason this isn't the default behavior that I'm missing? The only thing I can think that might be useful is to keep track of when an entity is constructed like this so you cannot accidentally save it and lose data.