Thursday, 8 August 2013

Django: Return foreign key's custom field value substitute for id number in filter()

Django: Return foreign key's custom field value substitute for id number
in filter()

I have below models.py
class site(models.Model):
site_name = models.CharField(max_length=10)
site_description = models.CharField(max_length=30, blank=True, null=True)
def __unicode__(self):
return self.site_name
class asset(models.Model):
STAT_CHOICES = (('Available', 'Available'), ('Deployed', 'Deployed'),
('Down', 'Down'))
asset_id = models.CharField(max_length=30, primary_key=True)
owner = models.CharField(max_length=30, blank=True, null=True)
status = models.CharField(choices=STAT_CHOICES, max_length=30, blank=True,
null=True)
site = models.ForeignKey(it_asset_site)
notes = models.CharField(max_length=300, blank=True, null=True)
def __unicode__(self):
return self.asset_id
As we known, table "site" would create site_id as PK by default. After i
imported data into table "asset" , In the django's admin, the "site" is
display "site_name". That effect is come by "def unicode(self):". So i
want to get the same effect for
f = asset.objects.filter(site__site_name__contains='NNG1')
But in the "f", "site" field display the number(site_id) not the
NNG1(site_name), the sample:
b = f.filter(site__site_name__contains='NNG1')
In [44]: b.values()[0]
Out[44]:
{'asset_id': u'3914100271',
'owner': u'',
'status': None,
'site_id': 8L,
'notes': u'',
}
Had a way to make the filter result become:
{'asset_id': u'3914100271',
'owner': u'',
'status': None,
'site_name': u'NNG1',
'notes': u'',
}
like the django admin page show? Thanks

No comments:

Post a Comment