我有一个Django模型类,如:
from django.db.models.deletion import PROTECT
from django.db.models import ForeignKey
class TScript(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32, null=False, blank=False, unique=True)
category = ForeignKey(TCategory, PROTECT, null=False, blank=False, to_field='name') # protect TScript from deletion; TScript belongs to TCategory
service = ForeignKey(TService, PROTECT, null=False, blank=False, to_field='name')
platform = ForeignKey(TPlatform, PROTECT, null=False, blank=False, to_field='name')
command = models.CharField(max_length=1024, blank=False, null=False)
machine = models.CharField(max_length=64, blank=False, null=False)
username = models.CharField(max_length=150, blank=False, null=False) # now save as string to avoid problem
supervisor = models.CharField(max_length=40, blank=True, null=False) # the supervisor of this user, fill in the form of script
interval = models.IntegerField(blank=False, null=False) # seconds
# oid = models.CharField(max_length=256, blank=False, null=False, default="1.3.6.1.4.1.41019.2.7.1.1.30.1")
timeout = models.IntegerField(blank=False, null=False) # seconds
status = models.IntegerField(blank=False, null=False)
out = models.CharField(max_length=1024, blank=True, null=True)
error = models.CharField(max_length=512, blank=True, null=True)
description = models.CharField(max_length=256, blank=True, null=True)
lastrundate = models.DateTimeField(null=True)
insertDate = models.DateTimeField(auto_now_add=True)
# overriding to save model with user of this session got from request, to fix
# '''Exception ValueError(u"save() prohibited to prevent data loss due to unsaved related object 'user'.",)'''
# def save_model(self, request, obj, form, change):
# obj.username = request.user.username
# super(TScript, self).save_model(request, obj, form, change)
def __unicode__(self): # __str__ on Python 3
return " - ".join(["ID: " + str(self.id), "Category: " + str(self.category), "Service: " + str(self.service), "Platform: " + str(self.platform),
"Command: " + self.command, "Machine: " + self.machine, "Username: " + str(self.username), "Supervisor: " + self.supervisor,
"Interval: " + str(self.interval), "Timeout: " + str(self.timeout), "Status: " + str(self.status),
"Out: " + self.out, "Error: " + self.error, "Description: " + self.description,
"Last run time: " + (datetime.strftime(self.lastrundate, const.DATE_FORMAT_FULL_YMDHSS) if self.lastrundate is not None else ""),
"Insert date: " + (datetime.strftime(self.insertDate, const.DATE_FORMAT_FULL_YMDHSS))
])
如您所见,它有一些ForeighKey
关联。它还有一个名为name
的属性,另一个属于id
。
现在,我有这个序列化器:
class TScriptSerializer(serializers.ModelSerializer):
class Meta:
model = TScript
fields = ('id', 'category', 'service', 'platform',
'command', 'machine', 'username', 'supervisor', 'interval', 'name',
'out', 'error', 'timeout', 'status', 'description',
'lastrundate', 'insertDate')
现在,当我向模板发送TScript
列表时,我在view.py
中有此功能:
@login_required
def manageralarm(req):
logger.info("MANAGERALARM Start HTML")
...
allScripts = operationsDB.getScripts() # retrieve all the TScripts
arrAllScripts = []
for sc in allScripts:
serSC = TScriptSerializer(sc)
arrAllScripts.append(serSC)
logger.info("array script list: " + repr(arrAllScripts))
return render(req, 'manageralarm.html',{"arrAlarms":arrAlarms,"SNMP_OID_GENERAL":config.SNMP_OID_TRAP,"arrOids":arrOids, "allScripts":arrAllScripts})
在模板中,我使用<select>
组合框进行渲染。
<select id="scriptCombo" name="scriptCombo" class="form-control" style="display: none" >
<option value="0" selected="selected"> - SELECT A SCRIPT TO ATTACH THE ALARM - </option>
{% for s in allScripts %}
<option value="{{s.id}}">{{s.name}}</option>
{% endfor %}
</select>
一切似乎都很好,但我在组合框中看到<BoundField>
,而不是name
的{{1}}。
为什么?
答案 0 :(得分:0)
好吧,最后事实证明序列化不是必需的,我只需要将列表传递给模板并完成。因此,不需要这些行:
arrAllScripts = []
for sc in allScripts:
serSC = TScriptSerializer(sc)
arrAllScripts.append(serSC)