A
A
alekssamos2021-03-10 06:31:21
Django
alekssamos, 2021-03-10 06:31:21

Logical editing of ForeignKey in admin panel?

Let's take an example from the documentation:

from django.db import models

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    
    reporter = models.ForeignKey(Reporter, related_name="article", on_delete=models.CASCADE) # **********

    def __str__(self):
        return self.headline

    class Meta:
        ordering = ('headline',)

In the admin panel, you can add a new Article, select or create a new Reporter.
But not vice versa.
I can add a Reporter, but there is no way to choose an Article.

Another example: there is one question and several possible answers.
So. If you open create a question in the admin panel, then you will not be able to add answers,
you will first need to add an answer, then select an existing / create a new question for it in the list.
from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, related_name="Choice", on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

If you do as it says in the tutorial, then the form for the survey will be in the admin panel, but not for the options.
But if in admin.py I register the model not Question, but Choice (, then I can add both polls and options, but only vice versa, first I add the option, then I create the question, and, so I will continue, first enter the option, then choose a question for him.
But I want the opposite.

Is it possible to do this?
I can get from one another, like Choice.question, and vice versa Question.choice

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-03-10
@bacon

But if in admin.py we register the model not Question, but Choice
register both
Well, study the docs on the admin panel, for example, this is https://docs.djangoproject.com/en/3.1/ref/contrib/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question