Tuesday, February 26, 2013

How to abstract model methods to a separate class?

Hi,

I have a model along the lines below. I want to be able to define some urls that have a related structure to provide different views of my model. It would be nice to abstract the link generation using a class as these views have wider application.

class MyModel(models.Model):

    date = models.DateField()
    slug = models.SlugField()

    def link_self(self):
        return "%s/%s/" % (self.date.year, self.slug)

    def link_view1(self):
        return "%s%s/" % (self.link_self(), 'view1')

    def link_view2(self):
        return "%s%s/" % (self.link_self(), 'view2')

I have tried to do the following, but the django template did not interpret the methods of my class correctly.

class myLinksClass:
    basepath = 'testing/'

    def self(self):
        return "%s" % (self.basepath, )

    def view1(self):
        return "%s%s" % (self.basepath, 'view1', )

    def view2(self):
        return "%s%s" % (self.basepath, 'view2', )

class MyModel(models.Model):

    date = models.DateField()
    slug = models.SlugField()

    def links(self):
        thelinks = myLinksClass
        return thelinks

Any advice on how to get the template to interpret the methods of myLinksClass?
Thanks,
R.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment