1
|
|
|
"""A module to lookup field of object.""" |
2
|
|
|
from __future__ import unicode_literals |
3
|
|
|
from collections import Iterable |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
def field_lookup(obj, field_path): |
7
|
|
|
""" |
8
|
|
|
Lookup django model field in similar way of django query lookup. |
9
|
|
|
|
10
|
|
|
Args: |
11
|
|
|
obj (instance): Django Model instance |
12
|
|
|
field_path (str): '__' separated field path |
13
|
|
|
|
14
|
|
|
Example: |
15
|
|
|
>>> from django.db import model |
16
|
|
|
>>> from django.contrib.auth.models import User |
17
|
|
|
>>> class Article(models.Model): |
18
|
|
|
>>> title = models.CharField('title', max_length=200) |
19
|
|
|
>>> author = models.ForeignKey(User, null=True, |
20
|
|
|
>>> related_name='permission_test_articles_author') |
21
|
|
|
>>> editors = models.ManyToManyField(User, |
22
|
|
|
>>> related_name='permission_test_articles_editors') |
23
|
|
|
>>> user = User.objects.create_user('test_user', 'password') |
24
|
|
|
>>> article = Article.objects.create(title='test_article', |
25
|
|
|
... author=user) |
26
|
|
|
>>> article.editors.add(user) |
27
|
|
|
>>> assert 'test_article' == field_lookup(article, 'title') |
28
|
|
|
>>> assert 'test_user' == field_lookup(article, 'user__username') |
29
|
|
|
>>> assert ['test_user'] == list(field_lookup(article, |
30
|
|
|
... 'editors__username')) |
31
|
|
|
""" |
32
|
|
|
if hasattr(obj, 'iterator'): |
33
|
|
|
return (field_lookup(x, field_path) for x in obj.iterator()) |
34
|
|
|
elif isinstance(obj, Iterable): |
35
|
|
|
return (field_lookup(x, field_path) for x in iter(obj)) |
36
|
|
|
# split the path |
37
|
|
|
field_path = field_path.split('__', 1) |
38
|
|
|
if len(field_path) == 1: |
39
|
|
|
return getattr(obj, field_path[0], None) |
40
|
|
|
return field_lookup(field_lookup(obj, field_path[0]), field_path[1]) |
41
|
|
|
|