class ArticleListView(ListView): model = Article(is_active=True) template_name = '../templates/index/article_list.html' context_object_name = 'articles' ordering = ['-pub_date']
时间: 2023-06-17 14:03:34 浏览: 51
这是一个 Django 中的 Class-Based View,名为 ArticleListView,它继承了 ListView。ListView 是一个基于模型的通用视图,它可以用来展示一个模型中的多个对象。在这里,我们指定了模型为 Article,且只展示 is_active=True 的文章。
template_name 属性指定了使用的模板文件,即 article_list.html。
context_object_name 属性指定了传递给模板的上下文变量的名称,即 articles。
ordering 属性用来指定文章的排序方式,这里是按照 pub_date 属性降序排列。
相关问题
Django如何让视图函数只选择Article的is_active属性等于true的 class ArticleListView(ListView): model = Article template_name = '../templates/index/article_list.html' context_object_name = 'articles' ordering = ['-pub_date']
你可以重写 `get_queryset` 方法来过滤 `is_active=True` 的文章,如下所示:
```python
class ArticleListView(ListView):
model = Article
template_name = '../templates/index/article_list.html'
context_object_name = 'articles'
ordering = ['-pub_date']
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(is_active=True)
```
这里我们调用了 `super().get_queryset()` 获取所有文章,然后使用 `filter(is_active=True)` 方法过滤出 `is_active=True` 的文章。这样就可以保证只有 `is_active=True` 的文章被返回给模板。
<TextView android:id="@+id/text_type" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_style" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_inventory_num" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent">如何隐藏
你可以在对应的 XML 文件中找到这些视图的定义,并设置它们的 visibility 属性为 "gone",这样它们就会被隐藏起来。例如:
```
<TextView
android:id="@+id/text_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/text_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/text_inventory_num"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
这样,前三个 TextView 就会被隐藏起来,只有 ListView 会显示出来。