Akhil Sahu
Akhil Sahu

Reputation: 637

How to fetch data of a particular id refrenced by foreign key django?

There a list of all the questions with correct and incorrect (scores if question is wrong and right) with Add button attached to each.

When I click add button the question are added to quiz into QuestionQuiz ,model along with their scores correct get +1 and incorrect -1 are updated to the database.

The corresponding quiz id is send thru the url in the form view image attached below: path('filter_list/<pk>',views.FilterQuestionView.as_view(),name='filter'),

What I want to achieve here is when page loads initially I want to show the scores for the corresponding question based on the quiz id fetched from database. How can I get all question title and description and if question added to quiz or not

What would be django way to achieve this ?

May be there's a to get all data including the ones already added in quiz like its currently fetching title,description rest fields are static

I could change fetch title,decription,correct,incorrect,flag(true if added to current quiz_id else false)

Image is attached

Here

Suppose a question is added to quiz. The text in the button must be ADDED and the correct and incorrect must be updated when the page is loaded initially. Here first question is added to the quiz. NOTE: Value = 1 is default values which is updated by user for correct and incorrect.

Following is model I have created:

class Question(models.Model):
	title = models.CharField(max_length=255 )
	description = models.TextField(max_length=300)
  

class Quiz(models.Model):
	name = models.CharField(max_length=225,blank=False )
	quiz_type =models.IntegerField(choices=QUIZ_TYPE,default=0)
    questions = models.ManyToManyField( Question, through='QuestionQuiz', related_name="quiz_question") 
	categories= models.ManyToManyField(Category,through='CategoryQuiz',related_name='quiz_category')		
 

class QuestionQuiz(models.Model):
	quiz = models.ForeignKey(Quiz,on_delete=models.CASCADE)
	question = models.ForeignKey(Question,on_delete=models.CASCADE)	
	correct =models.DecimalField(max_digits=4, decimal_places=3)
    incorrect= models.DecimalField(max_digits=4, decimal_places=3) 

	class Meta:
		unique_together = ('quiz','question')

Views.py - Used django_filter package to create filter

class FilterQuestionView( AddQuestionAjaxFormMixin,FormMixin,FilterView):
 
	form_class = QuestionQuizForm
	filterset_class =  QuestionFilter
	paginate_by = 5
	context_object_name = 'questions'
This is template :

{% for question in questions %}
   		<tr>
        <form method='POST'   id="q_{{question.id}}"> 
   		<td>{{question.title}}</td>
   		<td>{{question.description}}</td>
   	 

   		 
      <td><input type="text" value="1" id="correct_{{question.id}}"></td>

      <td><input type="text" value="1" id="incorrect_{{question.id}}"></td>
      <td> 
            <a id="btn_{{question.id}}" class="btn purple-gradient" onclick="addRemoveQuestion({{question.id}},{{quiz}})"  >Add</a>
       </td>
      </form>

Upvotes: 4

Views: 697

Answers (3)

Luky
Luky

Reputation: 31

You are using django_filter here. You can override its qs function in the QuestionFilter. This may help you extend your query in your way. The returned result could contain a flag suggesting its already added to quiz or not. Link reference contains the qs function extend detail. qs function

def qs(self): parent = super().qs d= parent.prefetch_related('quizquestion') return d

Upvotes: 3

Sara
Sara

Reputation: 21

You can use prefetch in order get data from related table in an inverse relationship

q = Question.objects.prefetch_related( 'questionquiz_set')

All question with quiz will be retrieved.

Upvotes: 2

Mohamed Moustafa
Mohamed Moustafa

Reputation: 33

I think you should edit your question a little bit to be more understandable because it's not clear yet for me. I am sorry I am not able to add comment due to the reputation. However, I don't know if you that answer or not but you can use

def get_context_data(self, *, object_list=None, **kwargs):
    context = super(FilterQuestionView, self).get_context_data(**kwargs)

then you can add whatever you query from the database in the context dictionary by creating the query that suits your case.

Check this link

Check this link to see how to create a good query.

I hope this could help.

Upvotes: 0

Related Questions