从Django中的数据库中获取正确的结果

时间:2018-03-30 13:27:47

标签: python django

我有三个Django模型如下:

class NewFeature(models.Model):
    application = models.CharField(max_length=50)
    name = models.CharField(max_length=250)
    start = models.DateTimeField(null=True, blank=True)
    stop = models.DateTimeField(null=True, blank=True)
    groups = models.ManyToManyField(to=Group)

class NewFeatureDetails(models.Model):
    new_feature = models.ForeignKey(to=NewFeature)
    culture = models.CharField(max_length=3, blank=False, default='en')
    text = models.TextField()
    picture = models.ImageField(upload_to=settings.MEDIA_ROOT, blank=False, null=False)

class NewFeatureRead(models.Model):
    new_feature = models.ForeignKey(to=NewFeature)
    user = models.ForeignKey(to=User)
    timeStamp = models.DateTimeField(auto_now=True)

因此start模型中的stopNewFeature可能为空,但它们也可能有值。

我想要来自NewFeatureDetails模型的所有记录user_idNewFeatureRead不存在:

  • current_time介于startstop之间NewFeature
  • 或仅存在start我只希望start < current_time
  • 的结果
  • 如果只有stop存在,我只想要current_time < stop
  • 的结果

我尝试的是这样的:

def getNewFeatures(request):
    current_user_id = request.user.id
    new_features = NewFeatureDetails.objects.exclude(new_feature__newfeatureread__user_id=current_user_id)
    if new_features:
        features = []
        for feature in new_features:
            start = feature.new_feature.start
            stop = feature.new_feature.stop
            current_time = datetime.datetime.now()

            // I'm stuck here    


        return new_features

有更好的方法吗?可以以某种方式在查询中完成吗?如果没有,我怎么能这样做,就像我试过的那样?

2 个答案:

答案 0 :(得分:0)

这是一个可能的解决方案,其中3个查询对应于您的3个点,并提供了目标NewFeature的ID列表。然后,您可以过滤NewFeatureDetails查询。

    q1 = NewFeature.objects.filter(start__isnull=False, end__isnull=False, start__lt=current_time, end__gt=current_time)
    q2 = NewFeature.objects.filter(start__isnull=False, end__isnull=True, start__lt=current_time)
    q3 = NewFeature.objects.filter(start__isnull=True, end__isnull=False, end__gt=current_time)
    fidlist = q1.union(q2, q3).distinct().values_list('id', flat=True)
    new_features = NewFeatureDetails.objects.exclude(
        new_feature__newfeatureread__user_id=current_user_id
        ).filter(new_feature_id__in=fidlist)

答案 1 :(得分:0)

from django.utils import timezone
NewFeatureDetails.objects.exclude(new_feature__newfeatureread__user_id=current_user_id,
                              new_feature__start__lte=timezone.now(),
                              feature__stop__gte=timezone.now() )

我已经为您写了这个基本查询。尝试一下,你可以改进它。您还可以使用__range来过滤日期范围