我只是从Django开始,目前停留在看似简单的需求/行为上。我想要一个页面,该页面具有基于该类的ForeignKey的一组过滤的条目,并从该其他类的呈现视图中调用。
我的model.py的简化版本是:
with DAG('bq_load_file_from_cloud_function', default_args=default_args) as dag:
def get_file_name_from_conf(ds, **kwargs):
fileName = kwargs['dag_run'].conf['fileName']
return [fileName]
get_file_name = PythonOperator(
task_id='get_file_name',
provide_context=True,
python_callable=get_file_name_from_conf)
# t1, t2 and t3 are examples of tasks created by instantiating operators
bq_load = GoogleCloudStorageToBigQueryOperator(
task_id='bq_load',
bucket='src_bucket',
#source_objects=['data.csv'],
source_objects=get_file_name.xcom_pull(context='', task_ids='get_file_name'),
destination_project_dataset_table='project:dataset.table',
write_disposition='WRITE_EMPTY')
bq_load.set_upstream(get_file_name)
我的view.py读为:
int k = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Controls.Add(
new Button()
{
Top = 50 + (50 * i),
Left = 50 + (50 * j),
Width = 50, Height = 50,
Text = (++k).ToString()
});
}
}
我的urls.py包含:
from django.db import models
class BookDay(models.Model):
bookdate = models.DateField()
bookevent = models.CharField(max_length=255)
class BookTime(models.Model):
booktime = models.TimeField()
bookdate = models.ForeignKey(BookDay, on_delete = models.CASCADE)
引用的days.html对此片段显示一组链接:
from django.http import HttpResponse
from django.views import generic
from .models import BookDay, BookTime
class DayView(generic.ListView):
template_name = 'booking/days.html'
context_object_name = 'bookdate_list'
def get_queryset(self):
return BookDay.objects.order_by('bookdate')
class TimeView(generic.ListView):
model = BookDay
template_name = 'booking/booktimes.html'
context_object_name = 'booktimes_list'
def get_queryset(self):
return BookTime.objects.filter(bookdate=bookday_id).order_by('booktime')
单击任何结果链接后,故障将显示为 from django.urls import path
from . import views
app_name = 'booking'
urlpatterns = [
path('', views.DayView.as_view(), name='bookdays'),
path('<int:pk>/', views.TimeView.as_view(), name='booktimes'),
]
。
我可以在上面的views.py中放置一个固定的整数代替{% for entry in bookdate_list %}
<li><a href="{% url 'booking:teetimes' entry.id %}">{{ entry.bookevent }}</a></li>
{% endfor %}
,它可以正常工作(显然,仅适用于该ForeignKey)。另外,我还反复使用filter()参数名称,相关的url和html,但无济于事。
我该如何设置参数以采用单击的链接并正确过滤BookTimes条目?我应该为此使用Django-filter,还是可以在Django中本地完成?
答案 0 :(得分:2)
就像错误所指出的那样,没有bookday_id
变量。如果我正确理解,您会对URL的pk
参数感兴趣。您可以在self.args
对象的self.kwargs
和View
中访问这些 positional 和 named 参数,因此可以将其重写为:
class TimeView(generic.ListView):
model = BookDay
template_name = 'booking/booktimes.html'
context_object_name = 'booktimes_list'
def get_queryset(self):
return BookTime.objects.filter(bookdate_id=self.kwargs['pk']).order_by('booktime')
由于pk
是int
,因此我们对bookdate_id
(此处为整数)进行过滤。
不过,我建议您将bookdate
外键重命名为bookday
(它所引用的模型的名称),因为现在它与{ {1}}模型。