我需要预取数据,但只能在django中使用

bbuxkriu  于 2023-01-21  发布在  Go
关注(0)|答案(1)|浏览(147)
class AppliedEvent(models.Model):

    event_type = models.ForeignKey(EventType, on_delete=models.CASCADE, related_name='applied_events', null=True)
    seedbed = models.ForeignKey(Seedbed, on_delete=models.CASCADE, null=True, related_name='applied_events')
    seed = models.ForeignKey(Seed, on_delete=models.CASCADE, related_name='applied_events', null=True)
    user = models.ForeignKey(UserModel, on_delete=models.CASCADE, related_name='applied_events', null=True)

class AppliedEventTime(models.Model):

    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    event = models.ForeignKey(AppliedEvent, on_delete=models.CASCADE, related_name='times')
    applied_by = models.ForeignKey(UserModel, on_delete=models.CASCADE, related_name='applied_times', null=True)

用户能够通过创建新的AppliedEventTime示例来添加新的事件时间。

class AppliedEventMixin:
    request: Any
    def get_queryset(self) -> QuerySet:
        return AppliedEvent.objects.filter(user_id=self.context.request.user).select_related(
        'user', 'event_type', 'seedbed', 'seed'
        ).only('user__username', 'event_type__name', 'seedbed__id', 'seed__id').prefetch_related(
        'times'
            )

这是我为django-extra控制器编写的查询集mixin

@api_controller('/applied_event', auth=JWTAuth(), permissions=[IsAuthenticated])
class AppliedEventController(AppliedEventMixin):
    @route.get('/applied_event/{event_id}', tags=['applied_event'], response=AppliedEventOutSchema)
    def event_by_id(self, event_id: int):
        event = get_object_or_404(self.get_queryset(), pk=event_id)

        return event

这是API和点的控制器。

class EventTypeNameSchema(Schema):
    id: int
    name: str

AppliedEventTimeSchema = create_schema(AppliedEventTime, exclude=['id', 'event'], custom_fields=[('applied_by', UserOutSchema, None)])

class UserOutSchema(Schema):
    id: int
    username: str

class AppliedEventOutSchema(ModelSchema):
    event_type: EventTypeNameSchema
    user: UserOutSchema
    times: List[AppliedEventTimeSchema]
    
    class Config:
        model = AppliedEvent
        include = ['id', 'seedbed', 'seed']

这是我的模式。
我尝试只预取最近添加的与Django项目中AppliedEvent相关的AppliedEventTime示例。我有一个AppliedEvent模型,它有一个指向AppliedEventTime模型的外键和一个用户外键,AppliedEventTime模型有一个指向AppliedEvent模型的外键和一个用户外键。

我的问题是,如何仅预取与AppliedEvent相关的最新添加的AppliedEventTime示例?

bxjv4tth

bxjv4tth1#

您可以使用order_by('-id')以降序对AppliedEventTime示例进行排序,并使用use first()方法获取最新添加的示例。

class AppliedEventMixin:
    request: Any
    def get_queryset(self) -> QuerySet:
        return AppliedEvent.objects.filter(user_id=self.context.request.user).select_related(
        'user', 'event_type', 'seedbed', 'seed'
        ).only('user__username', 'event_type__name', 'seedbed__id', 'seed__id').prefetch_related(
        Prefetch('times', queryset=AppliedEventTime.objects.order_by('-id').first())
            )

或者,你可以做的是修改类AppliedEventMixin以只预取与AppliedEvent相关的最新添加的AppliedEventTime示例。在上面的解决方案i中,用Prefetch...替换该行,提供如下:

Prefetch('times', queryset=AppliedEventTime.objects.latest())

相关问题