UPDATED ANSWER TO QUESTION: How do I get a lookup value (from Atc) to display on a transaction table (Drugs) when displaying Drug?
Solution, using Saverio’s approach of embedding the relationship in the model itself:
models.py
class Atc(models.Model):
id = models.CharField(max_length=60, primary_key=True, db_column='ID')
txt = models.CharField(max_length=690, db_column='TXT')
class Meta:
db_table = u'ATC'
def __unicode__(self):
return u"%s - %s" % (self.id, self.txt)
class Drug(models.Model):
id = models.CharField(max_length=64, primary_key=True, db_column='ID')
atc = models.ForeignKey(Atc, db_column='ATCCD')
pricetopharm = models.FloatField(db_column='PRICETOPHARM')
brandnm = models.CharField(max_length=135, db_column='BRANDNM')
drugnm = models.CharField(max_length=240, db_column='DRUGNM')
class Meta:
db_table = u'DRUGS'
def __unicode__(self):
return u"%s - %s" %(self.drugnm, self.formandstrength)
And in admin.py
class DrugsAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['id']}),
('ATC', {'fields': ['atc','brandnm'] }),
(None, {'fields': ['drugnm']}),
('Prices', {'fields': ['pricetopharm']}),
]
search_fields = ['drugnm','brandnm']
admin.site.register(Drug, DrugsAdmin)
admin.site.register(Atc)
The key points are to add to models.py
atc = models.ForeignKey(Atc, db_column='ATCCD')
to the Drug (transaction, not reference table) and
('ATC', {'fields': ['atc','brandnm'] }),
to the admin.py fieldsets to represent the many-to-one relationship.
Now, the contents of the admin.py is less relevant (which it should be in the MTV philosophy. Also, renaming the objects in the singular (Drug, not Drugs) was helpful, if nothing else other than it go rid of the duplicate s’s (ie. Drugs not Druggs).
The result is a display of drugs shows a dropdown box of id + txt eg. P04H11 – Cytotoxics
Thanks for your help guys
Pete
(too junior burger to answer my own questions, hence edit of original question!)
Why not just
This will display the related atc for your Drug instance right in the inlines part of the form.
(also, it could be interesting to note that generally django models are named in singular, as in
Druginstead ofDrugs. This is semantically correct withDrug.objects.filter(),drug = Drug()etc)Edit: further considerations on DB schema and data model
It seems that you have a previous DB schema to use. If you can’t change column names, you can at least give your attributes more meaningful names, so code is much more readable:
If you own also the DB schema, once the data model is complete, use something like South migrations (
db.rename(table_name, old_column_name, new_column_name)) to synchronize the schema to your now readable data model.