使用外键对模型进行Django分页

时间:2019-08-24 05:27:04

标签: django pagination django-pagination

发布和评论模型

class Post(models.Model):
    title = models.CharField(max_length=120)
    content = models.TextField()

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    content = models.TextField()

帖子详细信息的类视图

class PostDetailView(DetailView):
    model = Post
    context_object_name = 'post'
    template_name = 'posts/detail.html'

    def get_queryset(self, *args, **kwargs):
        request = self.request
        pk = self.kwargs.get('pk')
        queryset = Post.objects.filter(pk=pk)
        return queryset

在模板中,我这样做

{% for comment in post.comment_set.all %}
{% comment.content %}
{% endfor %}

通过这种方法,所有评论都显示在帖子详细信息页面中。但是,我想对帖子的评论进行分页,以便可以对评论进行分页,而不显示整个评论列表。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

默认情况下,在django中提供分页器。您可以通过像这样覆盖from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense classifier = Sequential() classifier.add(Conv2D(16, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) `classifier.add(MaxPooling2D(pool_size = (2, 2))) classifier.add(Conv2D(32, (3, 3), activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2)))` classifier.add(Conv2D(64, (3, 3), activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) classifier.add(Dense(units = 128, activation = 'relu')) classifier.add(Dense(units = 1, activation = 'sigmoid')) classifier.add(Flatten()) classifier.add(Dense(units = 128, activation = 'relu')) classifier.add(Dense(units = 1, activation = 'sigmoid')) classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) from keras.callbacks import TensorBoard # Use TensorBoard callbacks = TensorBoard(log_dir='./Graph') from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = train_datagen.flow_from_directory('dataset/training_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') test_set = test_datagen.flow_from_directory('dataset/test_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') classifier.fit_generator(training_set, steps_per_epoch = 100, epochs = 200, validation_data = test_set, validation_steps = 200) classifier.save('model.h5') 方法来对注释进行分页。

get_context_data

您可以像这样通过在模板上循环来显示commnet。

def get_context_data(self, **kwargs):
    context = super(PostDetailView, self).get_context_data(**kwargs)
    comments = context['post'].comment_set.all()
    paginator = Paginator(comments, per_page=50)
    page_number = 1  # get it from query sting or whatever the way you want
    page = paginator.page(page_number)
    context['comments'] = page
    return context

有关渲染分页控件的更多信息,请在此处查阅official docs about paginators