0
class Screening(models.Model):
  def get_omitted_1(self):
       return OmittedInformationReason.objects.get(pk=self.omitted_1).name 
  get_omitted_1 = property(get_omitted_1)

I want to have access to screening_instance.get_omitted_1 ,screening_instance.get_omitted_2 upto screening_instance.get_omitted_10. Is there better way to do this without creating get_omitted_1, get_omitted_2.. methods for each case like get_omitted_%d ??

I tried creating dynamic function at runtime but had some problem with it. I tried something like this:

def omitted_list(self,x):
    def omitted_function(self): 
        opk = "omitted_%d" % x
        return OmittedInformationReason.objects.get(pk=self.opk).name

    omitted_name = 'get_omitted_'+ str(x)

    setattr(self.__class__, omitted_name , omitted_function)
    omitted_name = property(omitted_name)

    for x in range(1, 3): 
      omitted_list(x)
3
  • I'm not sure why you believed that code would work... Commented Apr 30, 2012 at 8:12
  • Or why you think it would be a good idea in the first place. Commented Apr 30, 2012 at 8:20
  • I get AttributeError: 'Screening' object has no attribute 'get_omitted_1' with this code Commented Apr 30, 2012 at 9:12

2 Answers 2

1

I can't see any possible need for this. If you need dynamic access to items, use a method: that's what they're for.

def get_omitted(self, number):
    return OmittedInformationReason.objects.get(pk=number)
Sign up to request clarification or add additional context in comments.

1 Comment

By creating method like this, I wont be able to use it in django view for screening.get_omitted.1 So, dynamic method enables me to use in view as screening.get_omitted_1
0

By creating method like this, I wont be able to use it in django view for screening.get_omitted.1 So, dynamic method enables me to use in view as screening.get_omitted_1

Ah ha! You should have mentioned this in your original question. If you had others would have directed you to the documentation for creating custom tags which is the right way to solve your problem.

Once you have created your tag, in your template you can do {% get_omitted 1 %} and then {% get_omitted 2 %} and so on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.