django中取最后发布的记录

本文介绍如何使用Django ORM获取模型中的最新记录。通过设置`get_latest_by`属性,可以直接调用`latest()`方法获取指定字段的最大值对应的数据记录。此外,还介绍了如何在未设置`get_latest_by`的情况下手动指定字段获取最新记录。

get_latest_by
Models can have a get_latest_by attribute, which should be set to the name of a DateField or DateTimeField. If get_latest_by exists, the model's module will get a get_latest() function, which will return the latest object in the database according to that field. "Latest" means "having the date farthest into the future."

Model source code
from django.db import models

class Article(models.Model):
    headline = models.CharField(maxlength=100)
    pub_date = models.DateField()
    expire_date = models.DateField()
    class Meta:
        get_latest_by = 'pub_date'

    def __str__(self):
        return self.headline

class Person(models.Model):
    name = models.CharField(maxlength=30)
    birthday = models.DateField()

    # Note that this model doesn't have "get_latest_by" set.

    def __str__(self):
        return self.nameSample API usage
This sample code assumes the above models have been saved in a file mysite/models.py.

>>> from mysite.models import Article, Person

# Because no Articles exist yet, get_latest() raises ArticleDoesNotExist.
>>> Article.objects.latest()
Traceback (most recent call last):
    ...
DoesNotExist: Article matching query does not exist.

# Create a couple of Articles.
>>> from datetime import datetime
>>> a1 = Article(headline='Article 1', pub_date=datetime(2005, 7, 26), expire_date=datetime(2005, 9, 1))
>>> a1.save()
>>> a2 = Article(headline='Article 2', pub_date=datetime(2005, 7, 27), expire_date=datetime(2005, 7, 28))
>>> a2.save()
>>> a3 = Article(headline='Article 3', pub_date=datetime(2005, 7, 27), expire_date=datetime(2005, 8, 27))
>>> a3.save()
>>> a4 = Article(headline='Article 4', pub_date=datetime(2005, 7, 28), expire_date=datetime(2005, 7, 30))
>>> a4.save()

# Get the latest Article.
>>> Article.objects.latest()
<Article: Article 4>

# Get the latest Article that matches certain filters.
>>> Article.objects.filter(pub_date__lt=datetime(2005, 7, 27)).latest()
<Article: Article 1>

# Pass a custom field name to latest() to change the field that's used to
# determine the latest object.
>>> Article.objects.latest('expire_date')
<Article: Article 1>

>>> Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).latest('expire_date')
<Article: Article 3>

# You can still use latest() with a model that doesn't have "get_latest_by"
# set -- just pass in the field name manually.
>>> p1 = Person(name='Ralph', birthday=datetime(1950, 1, 1))
>>> p1.save()
>>> p2 = Person(name='Stephanie', birthday=datetime(1960, 2, 3))
>>> p2.save()
>>> Person.objects.latest()
Traceback (most recent call last):
    ...
AssertionError: latest() requires either a field_name parameter or 'get_latest_by' in the model

>>> Person.objects.latest('birthday')
<Person: Stephanie>
 

### Django前端框架推荐与集成方法 在构建基于Django的Web应用时,可以选择多种方式实现前后端分离或混合开发模式。以下是关于Django前端框架推荐及其集成方法的具体说明。 #### 推荐的前端框架 对于现代Web开发而言,Vue.js是一个非常流行的前端框架,尤其当其结合Element UI组件库时,能够快速搭建美观且功能强大的用户界面[^1]。除此之外,React和Angular也是常见的选择,具体决于团队的技术栈偏好以及项目的复杂度需求。 - **Vue.js**: Vue以其易上手性和灵活性著称,适合中小型项目或需要渐进式引入前端框架的应用场景。 - **React**: 如果项目规模较大并涉及复杂的UI交互逻辑,则React可能是更好的选项,因为它拥有丰富的生态系统和工具链支持。 - **Angular**: Angular适用于大型企业级应用程序开发,尽管它的学习曲线相对陡峭一些。 #### 集成方法概述 为了使Django作为后端服务提供商并与上述任一前端框架协同工作,通常采用RESTful架构风格设计API接口[^2]。下面详细介绍如何完成这一过程: ##### 后端部分 (Django REST Framework) 安装`djangorestframework`包并通过配置将其加入到您的INSTALLED_APPS列表中。接着定义模型类、序列化器以及视图集来暴露资源给客户端访问。 ```python # serializers.py from rest_framework import serializers from .models import MyModel class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' # views.py from rest_framework.viewsets import ModelViewSet from .serializers import MyModelSerializer from .models import MyModel class MyModelViewSet(ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer ``` 最后,在URL路由文件里注册相应的viewset即可让外部程序调用这些APIs。 ##### 前端部分 (以Vue为例) 创建一个新的Vue项目(可借助vue-cli脚手架),然后编写代码去请求刚才设置好的apis。利用axios这样的HTTP client发送GET/POST等类型的http requests至django backend server endpoint地址处获取所需的数据信息再展示出来。 ```javascript // main.js or component.vue import axios from 'axios'; export default { data() { return { items: [] }; }, mounted() { axios.get('http://your-django-site/api/my-model/') .then(response => this.items = response.data); } } ``` 以上便是基本的操作流程描述,当然实际操作过程中还需要考虑到跨域资源共享(CORS)等问题解决方案等内容。 #### 框架选择原则 无论选用哪种具体的前端技术方案,都应遵循如下几个通用准则来进行最终决策判断[^3]: - 主流程度:优先考虑那些被广泛接受使用的开源软件产品; - 社区活力状况:查看目标产品的github仓库活动记录情况比如提交次数频率等等指标衡量标准; - 功能匹配性评估:确认候选对象确实能满足业务层面提出的各项功能性诉求同时兼顾未来扩展可能性考量因素在里面; - 时间价观念体现:尽量挑选近期持续发布新版公告消息的产品版本号较高的那种类型比较好一点哦~; - 新手友好指数评分高低对比分析研究一下吧!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值