Title
Randle Taylor | Home
Go Home
Category
Description
Personal homepage and blog of Randle Taylor with posts on Programming and Science
Address
Phone Number
+1 609-831-2326 (US) | Message me
Site Icon
Randle Taylor | Home
Page Views
0
Share
Update Time
2022-05-02 09:32:14

"I love Randle Taylor | Home"

www.randlet.com VS www.gqak.com

2022-05-02 09:32:14

Randle Taylor Menu Home Blog Projects Papers & Talks Hire Me Looking up Django model fields from strings 2015-02-16 python django I recently needed to take Django field lookup/query strings andfind out what model field they were referencing. For example, imaginewe have the following models:class Business(models.Model): name = models.CharField(max_length=255) business_type = models.IntegerField(choices=zip(range(5), range(5)), default=1)class Department(models.Model): name = models.CharField(max_length=255) business = models.ForeignKey(Business)class Staff(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) department = models.ForeignKey(Department)I needed a function that would take a string likedepartment__business__business_type and returnthe Business.typefield (I needed to access the choices attribute of fields).Here's a short function which will do that sort of lookup:def find_field(cls, lookup): """Take a root class and a field lookup string and return the model field if it exists or raise a django.db.models.fields.FieldDoesNotExist if the field is not found.""" lookups = list(reversed(lookup.split("__"))) field = None while lookups: f = lookups.pop() # will raise FieldDoesNotExist exception if not found field = cls._meta.get_field(f) try: cls = field.rel.to except AttributeError: if lookups: # not all lookup fields were used # must be an incorrect lookup raise django.db.models.fields.FieldDoesNotExist(lookup) return field# use like:>> find_field(Staff, "department__business__business_type")>>>> find_field(Staff, "department__business")>>>> find_field(Staff, "department__foo")FieldDoesNotExist: Department has no field named 'foo'>> Comments About Hey I'm Randy and I live in Port Elgin, ON, Canada with my wife and two kids. I love writing software to create practical solutions to technical problems. You can see some of my work on my Projects page. Get in touch if you want to discuss how I can help your organization. Recent Posts Looking up Django model fields from strings Formatting floats to a specific number of significant digits in Python A Couple of Django South & SQL Server Migration Tips Asus N13 Windows 8 Drivers Prototyping Interfaces with Django (CBV version) BitBucket GitHub LinkedIn StackOverflow Email Copyright © 2012 randlet.com | email | sitemap | Powered by Python & Flask