我将这两个模型定义为一对多关系
来自django.core.validators导入RegexValidator 来自django.db导入模型
class Template(models.Model):
name = models.CharField(max_length=100)
fields = models.IntegerField()
def __str__(self):
return self.name
class Page(models.Model):
template = models.ForeignKey(Template, related_name='pages')
title = models.CharField(max_length=100)
text = []
for i in range(template.fields): #Error occuring here
text[i] = models.TextField()
def __str__(self):
return self.title
我想获得template.fields的值,但是我得到了这个错误
for i in range(template.fields):
AttributeError: 'ForeignKey' object has no attribute 'fields'
我使用的是ForeignKey对象错了吗?任何帮助将不胜感激
答案 0 :(得分:0)
您无法获取数据以迭代模板字段。如果您修改它,请使用__init__
功能。
class Template(models.Model):
name = models.CharField(max_length=100)
fields = models.IntegerField()
def __str__(self):
return self.name
class Page(models.Model):
template = models.ForeignKey(Template, related_name='pages')
title = models.CharField(max_length=100)
text = []
def __init__(self, request, *args,**kwargs):
super (Page,self ).__init__(*args,**kwargs)
self.fields['template'].queryset = Template.objects.all()
def __str__(self):
return self.title