Home > Blockchain >  Django, create table or page just to join all other tables into one and show it. is it possible?
Django, create table or page just to join all other tables into one and show it. is it possible?

Time:08-08

I want to show info from different tables together in another page or table. But I don't want create another table with duplicate info. Is it possible to Join many tables and show in some admin page?

class Answers(models.Model):
    Point = models.ForeignKey(Points, verbose_name="Point", on_delete=models.CASCADE, blank=True, null=True)
    Answers = models.TextField(verbose_name='Answers', blank=True, null=True)
    Rate = models.TextField(verbose_name='Rate', blank=True, null=True)
    Date = models.TextField(verbose_name='Date', blank=True, null=True)


    def __str__(self):
        return 'Answer '   str(self.Point.En_name)

    class Meta:
        db_table = 'Answers'
        verbose_name = 'Answer'
        verbose_name_plural = 'Moderation'

You can see class Answers and Text field Answers in it. In this field I have saved answers like:

"answer1
answer2
answer3"

I know it's bad, but there can be many answers, not fixed number, and I need create new table or page where I can see these answers like:

Question1 Question2 Question3
Answer1 Answer2 Answer3
2_Answer2 2_Answer2 2_Answer3

From all info of this model, from all rows. Is it Possible? Or I need duplicate info?

CodePudding user response:

Firstly, some improvements to your answer model:

class Answer(models.Model): # Django models should be singular, not plural
    question = models.ForeignKey(Question, ... # many-to-one relation to Question
    point = models.ForeignKey(Points, # should be 'Point' not 'Points'
    text = models.TextField(... # lower case and shouldn't clash with model name, imo
    rate = models.TextField(... # lower case
    date = models.TextField(... # ...

    ...

Set a foreign key relation to your question - this way you can have multiple answers to a single question, or just one.

If you want to get a 'table' of questions and answers then you can do this in views or templates:

questions = Question.objects.all()

for question in questions:
    answers = question.answer_set.all() # get all answers 

    for answer in answers:
        # do stuff
{% for question in questions %}
    {{ question }}
    {% for answer in question.answer_set.all %}
        {{ answer }}
    {% endfor %}
{% endfor %}
  • Related