我在Django中使用一种基本形式来收集用户的选择,这些选择将用于创建对象过滤器,然后输出到csv。我想使用表单中的值来访问不同模型中的数据。
我的表单看起来像这样。
class CustomReportForm(forms.Form):
CHOICES=[('Asset Labels','Asset Labels'),
('Asset List','Asset List')]
REPORT_FIELDS = [('id','ID'),
('name','Name'),
('location','Location'),
('status','Status'),
]
type = forms.ChoiceField(choices=CHOICES)
col_choices = forms.MultipleChoiceField(choices=REPORT_FIELDS, widget=forms.CheckboxSelectMultiple)
location = forms.ModelChoiceField(AssetLocation.objects.all(), required=False)
status = forms.ModelChoiceField(AssetStatus.objects.all(), required=False)
我有2个模型,分别以“ AssetLocation”和“ AssetStatus”的形式出现。
class AssetLocation(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
location = models.CharField(max_length=20)
location_code = models.CharField(max_length=10, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.company) + " - " + self.location
class AssetStatus(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
status = models.CharField(max_length=20)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.company) + " - " + self.status
我也有一个资产模型
class Asset(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
company = models.ForeignKey(Company, on_delete=models.CASCADE)
location = models.ForeignKey(AssetLocation, on_delete=models.CASCADE)
status = models.ForeignKey(AssetStatus, on_delete=models.CASCADE)
name = models.CharField(max_length=40)
def __str__(self):
return str(self.company) + " - " + self.name
我有一个访问POST数据的视图,并尝试使用该视图获取数据。
def AssetList(request):
assets = Asset.objects.all()
cols = request.POST.getlist('col_choices')
for a in assets:
data = []
for i in cols:
data.append(getattr(a,i))
print(data)
这按预期工作。我正在获取每个资产的位置和状态,但返回的是AssetLocation和AssetStatus的定义 str 。
我想访问AssetLocation.location和AssetStatus.status。
我尝试对此进行修改,但是它生成了一个'Asset'对象,没有属性'location.location'错误
REPORT_FIELDS = [('id','ID'),
('name','Name'),
('location.location','Location'),
('status.status','Status'),
]
如何使用getattr()函数访问外键值?
谢谢 詹姆斯
答案 0 :(得分:0)
您必须在查看代码时更加聪明。您可以尝试在select t.*, d.area
from hstT t left join
(select d.*, row_number() over (partition by id2 order by period asc) as seqnum
from hstD d
order by d.period asc
) d;
on d.id2 = t.id2 and seqnum = 1;
上进行拆分:
'.'
当然,如果您的关系不止一种,这会中断。