我想为django模型创建一个新类型的字段,它基本上是一个ListOfStrings。因此,在您的模型代码中,您将拥有以下内容:
models.py:
from django.db import models
class ListOfStringsField(???):
???
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ListOfStringsField() #
other.py:
myclass = myDjangoModelClass()
myclass.myName = "bob"
myclass.myFriends = ["me", "myself", "and I"]
myclass.save()
id = myclass.id
loadedmyclass = myDjangoModelClass.objects.filter(id__exact=id)
myFriendsList = loadedclass.myFriends
# myFriendsList is a list and should equal ["me", "myself", "and I"]
您将如何编写此字段类型,并遵守以下规定?
查看Django代码,看起来我想做类似于ForeignKey正在做的事情,但文档很少。
这导致以下问题:
这是来自question。
答案 0 :(得分:6)
有一些关于创建自定义字段here的非常好的文档。
然而,我认为你是在思考这个问题。听起来你实际上只是想要一个标准的外键,但是能够将所有元素作为单个列表检索。所以最简单的方法就是使用ForeignKey,并在模型上定义get_myfield_as_list
方法:
class Friends(model.Model):
name = models.CharField(max_length=100)
my_items = models.ForeignKey(MyModel)
class MyModel(models.Model):
...
def get_my_friends_as_list(self):
return ', '.join(self.friends_set.values_list('name', flat=True))
现在,在MyModel实例上调用get_my_friends_as_list()
将根据需要返回一个字符串列表。
答案 1 :(得分:5)
我也认为你这是错误的。试图让Django字段创建一个辅助数据库表几乎肯定是错误的方法。这样做很困难,如果你试图使你的解决方案普遍有用,可能会让第三方开发人员感到困惑。
如果你试图在一个列中存储非规范化数据blob,我会采用类似于你链接的方法,序列化Python数据结构并将其存储在TextField中。如果您希望Django以外的工具能够对数据进行操作,那么您可以序列化为JSON(或其他一些具有广泛语言支持的格式):
from django.db import models
from django.utils import simplejson
class JSONDataField(models.TextField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
if value is None:
return None
if not isinstance(value, basestring):
return value
return simplejson.loads(value)
def get_db_prep_save(self, value):
if value is None:
return None
return simplejson.dumps(value)
如果您只想要一个类似django Manager的描述符,它允许您操作与模型关联的字符串列表,那么您可以手动创建连接表并使用描述符来管理关系。这不完全是你需要的,但是this code should get you started。
答案 2 :(得分:5)
你所描述的声音对我来说与标签非常相似
那么,为什么不使用django tagging?
它就像一个魅力,你可以独立于你的应用程序安装它,它的API非常容易使用。
答案 3 :(得分:1)
感谢所有回答的人。即使我没有直接使用你的答案,例子和链接也让我朝着正确的方向前进。
我不确定这是否已准备就绪,但到目前为止它似乎在我的所有测试中都有效。
class ListValueDescriptor(object):
def __init__(self, lvd_parent, lvd_model_name, lvd_value_type, lvd_unique, **kwargs):
"""
This descriptor object acts like a django field, but it will accept
a list of values, instead a single value.
For example:
# define our model
class Person(models.Model):
name = models.CharField(max_length=120)
friends = ListValueDescriptor("Person", "Friend", "CharField", True, max_length=120)
# Later in the code we can do this
p = Person("John")
p.save() # we have to have an id
p.friends = ["Jerry", "Jimmy", "Jamail"]
...
p = Person.objects.get(name="John")
friends = p.friends
# and now friends is a list.
lvd_parent - The name of our parent class
lvd_model_name - The name of our new model
lvd_value_type - The value type of the value in our new model
This has to be the name of one of the valid django
model field types such as 'CharField', 'FloatField',
or a valid custom field name.
lvd_unique - Set this to true if you want the values in the list to
be unique in the table they are stored in. For
example if you are storing a list of strings and
the strings are always "foo", "bar", and "baz", your
data table would only have those three strings listed in
it in the database.
kwargs - These are passed to the value field.
"""
self.related_set_name = lvd_model_name.lower() + "_set"
self.model_name = lvd_model_name
self.parent = lvd_parent
self.unique = lvd_unique
# only set this to true if they have not already set it.
# this helps speed up the searchs when unique is true.
kwargs['db_index'] = kwargs.get('db_index', True)
filter = ["lvd_parent", "lvd_model_name", "lvd_value_type", "lvd_unique"]
evalStr = """class %s (models.Model):\n""" % (self.model_name)
evalStr += """ value = models.%s(""" % (lvd_value_type)
evalStr += self._params_from_kwargs(filter, **kwargs)
evalStr += ")\n"
if self.unique:
evalStr += """ parent = models.ManyToManyField('%s')\n""" % (self.parent)
else:
evalStr += """ parent = models.ForeignKey('%s')\n""" % (self.parent)
evalStr += "\n"
evalStr += """self.innerClass = %s\n""" % (self.model_name)
print evalStr
exec (evalStr) # build the inner class
def __get__(self, instance, owner):
value_set = instance.__getattribute__(self.related_set_name)
l = []
for x in value_set.all():
l.append(x.value)
return l
def __set__(self, instance, values):
value_set = instance.__getattribute__(self.related_set_name)
for x in values:
value_set.add(self._get_or_create_value(x))
def __delete__(self, instance):
pass # I should probably try and do something here.
def _get_or_create_value(self, x):
if self.unique:
# Try and find an existing value
try:
return self.innerClass.objects.get(value=x)
except django.core.exceptions.ObjectDoesNotExist:
pass
v = self.innerClass(value=x)
v.save() # we have to save to create the id.
return v
def _params_from_kwargs(self, filter, **kwargs):
"""Given a dictionary of arguments, build a string which
represents it as a parameter list, and filter out any
keywords in filter."""
params = ""
for key in kwargs:
if key not in filter:
value = kwargs[key]
params += "%s=%s, " % (key, value.__repr__())
return params[:-2] # chop off the last ', '
class Person(models.Model):
name = models.CharField(max_length=120)
friends = ListValueDescriptor("Person", "Friend", "CharField", True, max_length=120)
最终,我认为如果它被深入到django代码中并且更像ManyToManyField或ForeignKey,那么它仍然会更好。
答案 4 :(得分:-1)
我认为你想要的是custom model field。