Skip to content

This project has a field which extends a charfield and will pass the string stored in the database to the constructor of the object specified. Great for storing string used in a web request to create an object.

scrummyin/django-class-backed-field

Repository files navigation

django-class-backed-field

This field will allow you to store a string in the database and passes it as the first and only arg to a constructor. The best use I've found for this so far is the abbility to store the id of an object in the database, and then make a rest call using that id.

This is an example of a models.py you could create in your application.

from class_backed_field.fields import ClassBackedField

class OverSimplfiedGistPost(object):
    def __init__(self, gist_id):
        json_of_gist = requests.get("https://api.github.com/gists/%s" % gist_id).json()
        self.id = json_of_gist['id']
        self.text = [file_data['content'] for filename, file_data in json_of_gist['files'].items()]
        self.browser_url = json_of_gist['html_url']

id_retriving_lambda = lambda x: str(x.id)

class RemoteGist(models.Model):
    user = fields.ForgeinKey(User)
    gist = ClassBackedField(represents=OverSimplfiedGistPost, db_value_generator=id_retriving_lambda, max_length=255)

The model RemoteGist now is searchable using the id of the gist, or an instance of the gist. Also it will get the latest inforation form github everytime I use the object.

Examples of how usage:

my_gist = RemoteGist.objects.create(gist="5867996")
retrived_gist_from_string = RemoteGist.objects.get(gist="5867996")
instance_of_gist = OverSimplfiedGistPost("5867996")
retrived_gist_from_object = RemoteGist.object.get(gist=instance_of_gist)

print retrived_gist_from_string.gist.browser_url

About

This project has a field which extends a charfield and will pass the string stored in the database to the constructor of the object specified. Great for storing string used in a web request to create an object.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages