python - A simple database inner join using django -
i have 2 tables legacy database imported django app using inspectdb
here model definition
class appcosts(models.model): cost = models.decimalfield(max_digits=10, decimal_places=2) class appdefinitions(models.model): data = models.textfield() permissions = models.charfield(max_length=50, blank=true) appcost=models.onetoonefield(appcosts, db_column='id')
every app in appdefinitions has 1 entry in appcosts - 1 one relationship
when use select_related() :
>>> appdefinitions.objects.select_related().query.__str__() u'select _app_definitions.id, _app_definitions.data, _app_definitions.permissions, _app_definitions.id, _app_costs.id, _app_costs.cost _app_definitions inner join _app_costs on ( _app_definitions.id = _app_costs.id )' >>> = appdefinitions.objects.select_related().first() >>> a.id u'abaqus' >>> a.cost traceback (most recent call last): file "<console>", line 1, in <module> attributeerror: 'appdefinitions' object has no attribute 'cost' >>> a.appcost <appcosts: abaqus,1.50> >>> a.appcost.cost decimal('1.50')
now there 2 problems :
- the query pulls in id twice both fields (not big deal because table wont have more few hundred entries @ most, still, want right)
- i have access cost x.appcost.cost, rather x.cost
how achieve this?
i loath use custom sql, because defeat purpose of using django's orm in first place.
you want use django's orm, want diametrically opposed that, ie accessing cost x.cost
.
django not let that, since breaks object model. cost
attribute on appcosts model, not costs one. if it's bothering you, could add property
on costs returns self.appcosts.cost
, want long don't try use in queries.
Comments
Post a Comment