1👍
It works for me…
(dev) C:\work\dev\datakortet>cat maint\models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
class WordList(models.Model):
list_id = models.CharField(max_length=32, primary_key=True, default='42')
title = models.CharField(max_length=50)
user = models.ForeignKey(User, editable=False)
#...
def length(self):
return len([])
calling syncdb because I didn’t have the model in the db..
(dev) C:\work\dev\datakortet>python manage.py syncdb
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Synced:
...
> datakortet.maint
...
(dev) C:\work\dev\datakortet>cat tstwordlist.py
from django.contrib.auth.models import User
from maint.models import WordList
usr = User.objects.get(pk=1)
#WordList.objects.create(list_id=42, title='foo', user=usr)
wordlists = WordList.objects.filter(user=usr)
for w in wordlists:
print dir(w)
print w.length()
(dev) C:\work\dev\datakortet>python tstwordlist.py
['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', u'__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_base_manager', '_default_manager', '_deferred', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_set_pk_val', '_state', 'clean', 'clean_fields', 'date_error_message', 'delete', 'full_clean', 'length', 'list_id', 'objects', 'pk', 'prepare_database_save', 'save', 'save_base', 'serializable_value', 'title', 'unique_error_message', 'user', 'user_id', 'validate_unique']
0
adding a length2
(dev) C:\work\dev\datakortet>cat maint\models.py
...
class WordList(models.Model):
#...
def length(self):
return len([])
def length2(self):
return len([42])
don’t do a syncdb, but change the program to use length2 (and only print the keys in dir()
that start with length)..
(dev) C:\work\dev\datakortet>cat tstwordlist.py
...
wordlists = WordList.objects.filter(user=usr)
for w in wordlists:
print [name for name in dir(w) if name.startswith('length')]
print w.length2()
works as expected…
(dev) C:\work\dev\datakortet>python tstwordlist.py
['length', 'length2']
1
Source:stackexchange.com