楷模
from django.db import models
from django.utils import timezone
import datetime
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.FloatField(default=0)
# ...
def __str__(self):
return self.choice_text
创建
#from polls.models import Choice, Question;from django.utils import timezone
#q = Question(question_text="What's new?", pub_date=timezone.now());q.add(Choice(choice_text='variant', votes=0),Choice(choice_text='Not much', votes=0),Choice(choice_text='Just hacking again', votes=0),Choice(choice_text='The sky', votes=0));q.save;q = Question(question_text="m?", pub_date=timezone.now());q.save
#q = Question(question_text="Third question", pub_date=timezone.now());q.add(Choice(choice_text='single option', votes=0));q.save()
我要做的是通过 question_text 长度过滤问题,而不是选择数量(儿童):
#from django.db.models import Count,F, Func,Value
#q=Question.objects.all()
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{3}')#works
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(3)+'}')#works
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(F('no'))+'}')
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(F('nod'))+'}')
#q.filter(question_text__regex=r'.{'+str(F('choice__count'))+'}')
#q.filter(question_text__regex=r'.{'+str(Count('choice'))+'}')
#Question.objects.filter(question_text__regex = r'.{'+(str(Count('choice')))+'}')
#q.filter(question_text__regex=r'.{'+str(Count([1]))+'}')
#q.filter(question_text__regex=r'.{'+str(Count([1,2,2,2,2,2,2,2,2,2,2,2,2,2]))+'}')
#q.annotate(no=Func(F('question_text'), function='LENGTH')).filter(question_text__regex=r'.{'+str(F("no"))+'}')
#q.annotate(no=Func(F('question_text'), function='LENGTH')).filter(no__gte=F('choice__count'))#works
#q.filter(question_text__regex=r'.{'+str(F("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(Count("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(Count("choice"))+'}')
#q.filter(question_text__regex=r'.{'+str(Value("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(Value("choice__count"))+'}')