我目前正在制作一个python代码生成器来快速模拟django项目。
我有一个包含所有模型数据的xml文件。从那里它将消失并模拟模型,通用视图,模板等与jinja2。
我正在努力让jinja访问dicts中的嵌套列表。
code_gen.py
public class YourActivity extends Activity implements EndlessScrollListener
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
EndlessScrollView myScrollView = (EndlessScrollView) findViewById(R.id.my_scroll_view);
myScrollView.setScrollViewListener(this);
}
@Override
public void onScrollChanged(EndlessScrollView scrollView, int x, int y, int oldx, int oldy)
{
// We take the last son in the scrollview
View view = scrollView.getChildAt(scrollView.getChildCount() - 1);
int distanceToEnd = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));
// if diff is zero, then the bottom has been reached
if (distanceToEnd == 0) {
// do stuff your load more stuff
}
}
}
models.xml
models = {}
tree = ET.parse('models.xml')
root = tree.getroot()
for child in root:
models[child.tag] = []
for c in child:
models[child.tag].append(c.tag)
print models
t = Template("""from django.db import models
{% for class in model %}
class {{ class }}(models.Model):
{% for occurrence in occurrences %}{{ occurrence }}{% endfor %}
{% endfor %}
""")
i = t.render(model=models)
fo = open('test.py', 'wb')
fo.write(i)
fo.close()
如果我打印出模型,我会得到:
<?xml version="1.0" encoding="UTF-8"?>
<Models>
<Model1>
<CharField max_length="10" null="True" blank="True">Firstname</CharField>
<IntegerFieldnull null="True" blank="True">age</IntegerField>
</Model1>
<Model2>
<EmailField max_length="10" null="True" blank="True">email</EmailField>
<DateField null="True" blank="True">DOB</DateField>
</Model2>
</Models>
当我将它添加到模板时,我获得了类名但没有任何字段。
答案 0 :(得分:3)
问题是您使用的是{% for occurrence in occurrences %}
,但是您没有在任何地方设置occurrences
。
最简单的解决方法是遍历字典中的项目,然后同时拥有键(模型)和值(字段列表)。
{% for class, occurences in model.items() %}
class {{ class }}(models.Model):
{% for occurrence in occurrences %}{{ occurrence }}{% endfor %}
{% endfor %}