• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.Question类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中questions.models.Question的典型用法代码示例。如果您正苦于以下问题:Python Question类的具体用法?Python Question怎么用?Python Question使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Question类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_from_url

    def test_from_url(self):
        """Verify question returned from valid URL."""
        q = question(save=True)

        eq_(q, Question.from_url('/en-US/questions/%s' % q.id))
        eq_(q, Question.from_url('/es/questions/%s' % q.id))
        eq_(q, Question.from_url('/questions/%s' % q.id))
开发者ID:DWDRAEGER,项目名称:kitsune,代码行数:7,代码来源:test_models.py


示例2: handle

    def handle(self, *args, **options):

        Question.objects.all().delete()
        Answer.objects.all().delete()
        print('Deleted existing data')

        answers = []
        with open(settings.BASE_DIR + '/../' + self.csv_file, 'r') as csvfile:
            reader = csv.reader(csvfile, delimiter='|')
            next(reader, None)

            for row in reader:

                if(len(answers) > 80):
                    save_answers(answers)
                    answers = []


                q = Question(question=row[0])
                q.save()

                print('Saved question with id ' + str(q.id));

                answers.append(Answer(question=q, choice=row[1], correct=True))

                for i in row[2].split(','):
                    answers.append(Answer(question=q, choice=i, correct=False))

        save_answers(answers)
开发者ID:agronick,项目名称:WebServiceExample,代码行数:29,代码来源:populate_db.py


示例3: test_cron_updates_counts

    def test_cron_updates_counts(self):
        q = question(save=True)
        self.refresh()

        eq_(q.num_votes_past_week, 0)
        # NB: Need to call .values_dict() here and later otherwise we
        # get a Question object which has data from the database and
        # not the index.
        document = (Question.search()
                            .values_dict('question_num_votes_past_week')
                            .filter(id=q.id))[0]
        eq_(document['question_num_votes_past_week'], 0)

        vote = questionvote(question=q, anonymous_id='abc123')
        vote.save()
        q.num_votes_past_week = 0
        q.save()

        update_weekly_votes()
        self.refresh()

        q = Question.objects.get(pk=q.pk)
        eq_(1, q.num_votes_past_week)

        document = (Question.search()
                            .values_dict('question_num_votes_past_week')
                            .filter(id=q.id))[0]
        eq_(document['question_num_votes_past_week'], 1)
开发者ID:LASarkar,项目名称:kitsune,代码行数:28,代码来源:test_votes.py


示例4: ask

def ask(request):
    ask_form = AskQuestion(request.POST or None)
    args = {}
    args['form'] = ask_form
    if request.POST and ask_form.is_valid():
        question = Question(text=ask_form.cleaned_data['text'], title=ask_form.cleaned_data['title'])
        tags = ask_form.cleaned_data['tags']

        g = Tag.objects.all()
        getTag = tags.split(', ')

        for tag in getTag:
            counter = 0
            for l in g:
                if l.tag == tag:
                    counter += 1
            if counter == 0:
                t = Tag(tag=tag)
                t.save()


        user = auth.get_user(request)
        question.author = user

        question.save()
        a = g.filter(tag__in=getTag)
        question.tags.add(*a)
        return redirect('questionGet', question_id=question.id)

    else:
        return render(request, 'ask.html', args)
开发者ID:Zanexess,项目名称:AskingHeapProject,代码行数:31,代码来源:views.py


示例5: gradeQuestion

def gradeQuestion(request):
	questionList = json.loads(request.POST['questions'])
	for question in questionList:
		sentenceText = question['sentence']
		questionText = question['question']
		labelText = question['label']
		gradeVal = question['grade']
		if Sentence.objects.filter(text=sentenceText).exists() :
			sentence = Sentence.objects.get(text=sentenceText)
		else:
			sentence = Sentence(text=sentenceText)
			sentence.save()

		if Question.objects.filter(text=questionText).exists():
			question = Question.objects.get(text=questionText)
		else:
			question = Question(text=questionText)
			question.save()

		if Label.objects.filter(text=labelText).exists():
			label = Label.objects.get(text = labelText)
		else:
			label = Label(text = labelText)
			label.save()
		grade = Grade(sentence=sentence,question=question,label=label,grade=gradeVal)
		grade.save()
	return HttpResponse('200')
开发者ID:mickeyinfoshan,项目名称:django-swuquestion,代码行数:27,代码来源:views.py


示例6: auto_lock_old_questions

def auto_lock_old_questions():
    """Locks all questions that were created over 180 days ago"""
    # Set up logging so it doesn't send Ricky email.
    logging.basicConfig(level=logging.ERROR)

    # Get a list of ids of questions we're going to go change. We need
    # a list of ids so that we can feed it to the update, but then
    # also know what we need to update in the index.
    days_180 = datetime.now() - timedelta(days=180)
    q_ids = list(Question.objects.filter(is_locked=False)
                                 .filter(created__lte=days_180)
                                 .values_list('id', flat=True))

    if q_ids:
        log.info('Updating %d questions', len(q_ids))

        sql = """
            UPDATE questions_question
            SET is_locked = 1
            WHERE id IN (%s)
            """ % ','.join(map(str, q_ids))

        cursor = connection.cursor()
        cursor.execute(sql)
        transaction.commit_unless_managed()

        if settings.ES_LIVE_INDEXING:
            try:
                es = get_es()

                # So... the first time this runs, it'll handle 160K
                # questions or so which stresses everything. Thus we
                # do it in chunks because otherwise this won't work.
                #
                # After we've done this for the first time, we can nix
                # the chunking code.

                from search.utils import chunked
                for chunk in chunked(q_ids, 1000):

                    # Fetch all the documents we need to update.
                    es_docs = get_documents(Question, chunk)

                    log.info('Updating %d index documents', len(es_docs))

                    # For each document, update the data and stick it
                    # back in the index.
                    for doc in es_docs:
                        doc[u'question_is_locked'] = True
                        Question.index(doc, bulk=True, es=es)

                    es.flush_bulk(forced=True)
                    es.refresh(WRITE_INDEX, timesleep=0)

            except ES_EXCEPTIONS:
                # Something happened with ES, so let's push index updating
                # into an index_task which retries when it fails because
                # of ES issues.
                index_task.delay(Question, q_ids)
开发者ID:deimidis,项目名称:kitsune,代码行数:59,代码来源:cron.py


示例7: test_question_no_answers_deleted

    def test_question_no_answers_deleted(self):
        q = question(title=u'Does this work?', save=True)
        self.refresh()
        eq_(Question.search().query('work').count(), 1)

        q.delete()
        self.refresh()
        eq_(Question.search().query('work').count(), 0)
开发者ID:Curlified,项目名称:kitsune,代码行数:8,代码来源:test_es.py


示例8: test_is_recent_with_recent_question

	def test_is_recent_with_recent_question(self):
		"""
		is_recent() should return True for
		questions whose pub_date is within the last day
		"""
		time = timezone.now() - datetime.timedelta(hours=1)
		recent_question = Question(pub_date=time)
		self.assertEqual(recent_question.is_recent(), True)
开发者ID:EdgeCaseBerg,项目名称:whoseopinion.com,代码行数:8,代码来源:tests.py


示例9: test_is_recent_with_future_question

	def test_is_recent_with_future_question(self):
		"""
		is_recent() should return False for questions whose
		pub_date is in the future
		"""
		time = timezone.now() + datetime.timedelta(days=30)
		future_question = Question(pub_date=time)
		self.assertEqual(future_question.is_recent(),False)
开发者ID:EdgeCaseBerg,项目名称:whoseopinion.com,代码行数:8,代码来源:tests.py


示例10: test_from_invalid_url

    def test_from_invalid_url(self):
        """Verify question returned from valid URL."""
        q = question(save=True)

        eq_(None, Question.from_url('/en-US/questions/%s/edit' % q.id))
        eq_(None, Question.from_url('/en-US/kb/%s' % q.id))
        eq_(None, Question.from_url('/random/url'))
        eq_(None, Question.from_url('/en-US/questions/stats'))
开发者ID:DWDRAEGER,项目名称:kitsune,代码行数:8,代码来源:test_models.py


示例11: test_notification_created

    def test_notification_created(self):
        """Creating a new question auto-watches it for answers."""

        u = User.objects.get(pk=118533)
        q = Question(creator=u, title='foo', content='bar')
        q.save()

        assert QuestionReplyEvent.is_notifying(u, q)
开发者ID:Akamad007,项目名称:kitsune,代码行数:8,代码来源:test_models.py


示例12: test_is_recent_with_old_questions

	def test_is_recent_with_old_questions(self):
		"""
		is_recent() should return False for questions 
		whose pub_date is older than 1 day
		"""
		time = timezone.now() - datetime.timedelta(days=30)
		old_question = Question(pub_date=time)
		self.assertEqual(old_question.is_recent(), False)
开发者ID:EdgeCaseBerg,项目名称:whoseopinion.com,代码行数:8,代码来源:tests.py


示例13: test_notification_created

    def test_notification_created(self):
        """Creating a new question auto-watches it."""

        u = User.objects.get(pk=118533)
        q = Question(creator=u, title='foo', content='bar')
        q.save()

        assert check_watch(Question, q.id, u.email, 'reply')
开发者ID:chowse,项目名称:kitsune,代码行数:8,代码来源:test_models.py


示例14: update_question_vote_chunk

def update_question_vote_chunk(data):
    """Update num_votes_past_week for a number of questions."""

    # First we recalculate num_votes_past_week in the db.
    log.info('Calculating past week votes for %s questions.' % len(data))

    ids = ','.join(map(str, data))
    sql = """
        UPDATE questions_question q
        SET num_votes_past_week = (
            SELECT COUNT(created)
            FROM questions_questionvote qv
            WHERE qv.question_id = q.id
            AND qv.created >= DATE(SUBDATE(NOW(), 7))
        )
        WHERE q.id IN (%s);
        """ % ids
    cursor = connection.cursor()
    cursor.execute(sql)
    transaction.commit_unless_managed()

    # Next we update our index with the changes we made directly in
    # the db.
    if data and settings.ES_LIVE_INDEXING:
        # Get the data we just updated from the database.
        sql = """
            SELECT id, num_votes_past_week
            FROM questions_question
            WHERE id in (%s);
            """ % ids
        cursor = connection.cursor()
        cursor.execute(sql)

        # Since this returns (id, num_votes_past_week) tuples, we can
        # convert that directly to a dict.
        id_to_num = dict(cursor.fetchall())

        try:
            # Fetch all the documents we need to update.
            from questions.models import Question
            from search import es_utils
            es_docs = es_utils.get_documents(Question, data)

            # For each document, update the data and stick it back in the
            # index.
            for doc in es_docs:
                # Note: Need to keep this in sync with
                # Question.extract_document.
                num = id_to_num[int(doc[u'id'])]
                doc[u'question_num_votes_past_week'] = num

                Question.index(doc)
        except ES_EXCEPTIONS:
            # Something happened with ES, so let's push index updating
            # into an index_task which retries when it fails because
            # of ES issues.
            index_task.delay(Question, id_to_num.keys())
开发者ID:LASarkar,项目名称:kitsune,代码行数:57,代码来源:tasks.py


示例15: setUp

    def setUp(self):
        super(TestQuestionMetadata, self).setUp()

        # add a new Question to test with
        question = Question(title='Test Question',
                            content='Lorem Ipsum Dolor',
                            creator_id=1)
        question.save()
        self.question = question
开发者ID:Akamad007,项目名称:kitsune,代码行数:9,代码来源:test_models.py


示例16: test_no_inactive_users

 def test_no_inactive_users(self):
     """Ensure that inactive users' questions don't appear in the feed."""
     u = User.objects.get(pk=118533)
     u.is_active = False
     u.save()
     q = Question(title='Test Question', content='Lorem Ipsum Dolor',
                  creator_id=118533)
     q.save()
     assert q.id not in [x.id for x in QuestionsFeed().items()]
开发者ID:Akamad007,项目名称:kitsune,代码行数:9,代码来源:test_feeds.py


示例17: get_queryset

 def get_queryset(self):
     if 'sort' in self.request.GET.keys():
         if self.request.GET['sort']=='title':
             return Question.get_query_sorted_by_title()
         if self.request.GET['sort']=='date':
             return Question.get_query_sorted_by_publish_date()
         if self.request.GET['sort']=='likes':
             return Question.get_query_sorted_by_likes()
     return Question.objects.all()
开发者ID:eivae2iz,项目名称:technotrack_web,代码行数:9,代码来源:views.py


示例18: handle

    def handle(self, *args, **options):
        users = list(User.objects.all())

        for i in range(10):
            t = Topic()
            t.name = u'Topic Name {}'.format(i)
            t.description = u'Topic Description {}'.format(i)
            t.save()
        topics = list(Topic.objects.all())

        for j in range(100):
            q = Question()
            q.author = random.choice(users)
            q.title = u'title {}'.format(j)
            q.text = u'text {}'.format(j)
            q.pub_date = datetime.datetime.now()
            q.is_published = True
            q.save()
            q.topics = random.sample(topics, random.randint(1, 6))
        questions = list(Question.objects.all())

        for k in range(100):
            c = Comment()
            c.author = random.choice(users)
            c.question = random.choice(questions)
            c.text = u'text {}'.format(k)
            c.pub_date = datetime.datetime.now()
            c.save()
开发者ID:PhilSk,项目名称:src,代码行数:28,代码来源:data_filling.py


示例19: create_question

 def create_question(self, name):
     user = UserWithAvatar.objects.order_by("?")[:1][0]
     pub_date = timezone.now()
     title = "Could you help me with " + name + "?"
     text = self.lorem * 10
     tags = Tag.objects.order_by("?")[:5]
     question = Question(author=user, pub_date=pub_date, text=text, title=title)
     question.save()
     for tag in tags:
         question.tags.add(tag)
     question.save()
开发者ID:Oktosha,项目名称:askPupkin,代码行数:11,代码来源:filldata.py


示例20: test_question_questionvote

    def test_question_questionvote(self):
        # Create a question and verify it doesn't show up in a
        # query for num_votes__gt=0.
        q = question(title=u'model makers will inherit the earth', save=True)
        self.refresh()
        eq_(Question.search().filter(num_votes__gt=0).count(), 0)

        # Add a QuestionVote--it should show up now.
        questionvote(question=q, save=True)
        self.refresh()
        eq_(Question.search().filter(num_votes__gt=0).count(), 1)
开发者ID:Curlified,项目名称:kitsune,代码行数:11,代码来源:test_es.py



注:本文中的questions.models.Question类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.QuestionVote类代码示例发布时间:2022-05-26
下一篇:
Python models.Answer类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap