How do you add a model method to an existing class within an interactive session (in iPython)?

StackOverflow https://stackoverflow.com/questions/1143833

  •  16-09-2019
  •  | 
  •  

Question

I have a basic model:

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    state = USStateField() 

I start up an iPython session with:

$ python manage.py shell
>>> from app.models import Person

How do I add this model method within the iPython session?

>>>    def is_midwestern(self):  
...        "Returns True if this person is from the Midwest."  
...        return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')  

>>> person = Person.objects.filter(last_name='Franklin')
>>> person.is_midwestern
True

I want to be able to test these model methods without having to add the method to the models.py file and then restarting the iPython shell session.

I seem to be doing something wrong because when I add a new model method in an interactive session, it doesn't seem to be linked to the class like it does when the model method is defined in a file.

So if I created the model method as above and attempted to use it. e.g. ' >>> person = Person.objects.filter(last_name='Franklin')
>>> person.is_midwestern
'Person' object has no attribute
'is_midwestern'`

Was it helpful?

Solution

why can't you just do this Person.is_midwestern = is_miswestern e.g.

>>> class Person:
...     def __init__(self): self.mid = True
... 
>>> def is_midwestern(self): return self.mid
... 
>>> Person.is_midwestern = is_midwestern
>>> p = Person()
>>> p.is_midwestern()

True
>>> 

OTHER TIPS

The accepted answer gave me an error, but from this blog post, I used the following method and it worked.

from types import MethodType
Person.is_midwestern = MethodType(is_midwestern, p)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top