【问题标题】:In model save() how to get all field starting with 'foo'在模型 save() 中如何获取以 'foo' 开头的所有字段
【发布时间】:2010-02-22 21:19:53
【问题描述】:

我有这个 django 模型:

from django.db import models

class MyModel(models.Model):
    foo_it = model.CharField(max_length=100)
    foo_en = model.CharField(max_length=100)

    def save(self):
        print_all_field_starting_with('foo_')
        super(MyModel, self).save()

所以我想获取以 foo 开头的所有字段(例如)并用它做一些事情。 我不能在代码中这样做,因为我不知道模型中的所有字段(我正在使用 django-transmeta)

那么,我该怎么做呢?

提前致谢 ;)

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    get_all_field_names() 方法内置于所有模型的Meta 子类中,可以在foo._meta.get_all_field_names() 中找到:

    >>> from foo.models import Foo
    >>> f = Foo.objects.get(pk=1)
    >>> f._meta.get_all_field_names()
    ['active', 'created', 'expires', 'id', , 'inputter', 'reason', 'requester', 'updated']
    

    所以这将是一件简单的事情:

    def print_all_fields_starting_with(obj, starter):
        fields = [x for x in obj._meta.get_all_field_names() if x.startswith(starter)]
        for field in fields:
            print getattr(obj, field)
    

    在你的自定义save():

    def save(self):
        print_all_fields_starting_with(self, "foo_")
        super(MyModel, self).save()
    

    【讨论】:

    • 酷!很好的解决方案:D 谢谢;)
    【解决方案2】:

    这可以解决问题,尽管您还需要传入要打印其字段的对象:

    import inspect
    def print_all_field_starting_with(prefix, object):
        for name, value in inspect.getmembers(object):
            if name.startswith(prefix):
                print name # or do something else
    

    请参阅documentation for the inspect module 了解更多信息。

    【讨论】:

    • 不,它不起作用 :( 我收到一个错误:无法通过 Post 实例访问管理器。不过,谢谢。
    • 貌似有一个Django票与这个错误相关:code.djangoproject.com/ticket/12568
    【解决方案3】:

    你可以这样做:

    for field in dir(self):
        if field.startswith('foo_'):
          # getting with getattr(self, field)
          # setting with setattr(self, field, value)
    

    如果您想获取字段列表,您也可以这样做:

    foo_fields = [field for field in dir(self) if field.startswith('foo_')]
    

    或者打印foo字段的值列表:

    print map(lambda x: getattr(self, x), [field for field in dir(self) if field.startswith('foo_')])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-05
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 2015-08-09
      相关资源
      最近更新 更多