我想将过滤后的查询集存储在列表中,然后遍历模板中的列表。
我的模型中有一个租户列表,如下所示:
def expiry(request):
now = datetime.datetime.now()
tenant_queryset = Tenant.objects.all()
expired_list = []
for x in range(0, 12):
date = now + relativedelta(months=x)
expired = tenant_queryset.filter(
contract_end__year=date.year,
contract_end__month=date.month
)
expired_list.append(expired)
context = {"expired_list": expired_list}
return render(request, "expired_template.html", context)
查看如下:
{% for tenant in expired_list %}
{{ tenant.first_name }}<br>
{{ tenant.telephone }}<br>
{{ tenant.contract_end }}<br>
{% endfor %}
模板:
private void sendNotificatin(String title, String message) {
private void sendNotificatin(String title, String message) {
Intent intent = new Intent(this,SplashScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent, PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.app_ic)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(sound) // changed from SET_DEFAULTS
.setContentIntent(pendingIntent);
/* Begin other added stuff */
.setLights(0xffff0000, 500, 250);
.setWhen(System.currentTimeMillis())
/* End other added stuff */
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Random random = new Random();
int num = random.nextInt(99999-1000)+1000;
notificationManager.notify(num,notificationBuilder.build());
}
我在视图中使用for循环来完成一年中的几个月,然后将这些结果存储在列表中。
我似乎无法在我的模板中显示tenant.first_name,tenant.last_name,tenant.telephone和tenant.contract_end值。我猜测这是因为我已经将我过滤的查询集的结果输出到列表中并显示那些结果而不是“引用”,如果这是有意义的。
我该如何解决这个问题?
感谢您的帮助。
答案 0 :(得分:0)
这是因为您每次都会在expired_list
和QuerySet
中追加。
将append
更改为:
expired_list += expired
这样,你最终得到一个统一的(扁平的)QuerySet
(列表)。
Python(非常简单)示例:
list_1 = []
list_2 = [1, 2, 3]
list_1.append(list_2)
print(list_1) # [[1, 2, 3]]
list_1 = []
list_2 = [1, 2, 3]
list_1 += list_2
print(list_1) # [1, 2, 3]