views:

57

answers:

1

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'`

+2  A: 

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
>>>
Anurag Uniyal
That's what I was looking for. Thanks :-)
BryanWheelock
good :) so you can select it as an answer
Anurag Uniyal