Search code examples
pythondjangoadminmodels

How to format OneToOne Relationship in Django Admin?


I have 2 models that are connected via a OneToOneField Relationship. This is what they look like:

class UserText(models.Model):
    user_input = models.CharField(max_length=2000)

class Question(models.Model):
    user_text = models.OneToOneField(
        UserText,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )
    user_questions = models.CharField(max_length=2000)

I would like each UserText to have the Questions model connected to it within the database. This is why I used a OneToOne relationship. From here, I do not know how to represent this relationship within my admin.py so that when I look in my database through the admin I see each UserText model with its connected Question. This is what my admin.py look as of now:

from django.contrib import admin
from v2.models import UserText
from v2.models import Question

@admin.register(UserText)
class UserTextAdmin(admin.ModelAdmin):
    model = UserText
    display = ('user_input')

@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    model = Question
    display = ('user_questions')

What do I need to add or change in my admin.py so that every Question model is connected to it's parent UserText model through the OneToOne relationship?


Solution

  • You just need to call the correct related field.

    If you are inside the Question Admin Interface you need to add the user_textto your form:

    @admin.register(Question)
    class QuestionAdmin(admin.ModelAdmin):
        ...
        fields = ('user_text', ...)
    

    If you are inside the UserText Admin Interface you can use inlines:

    class QuestionInline(admin.TabularInline):
        model = Question
    
    @admin.register(UserText)
    class UserTextAdmin(admin.ModelAdmin):
        ...
        inlines = [QuestionInline, ]
    

    Btw, a OneToOneField is similar a ForeignKey with unique=True, in other words, each user can only have one question. If the user can have more than one question you should switch to a ForeignKey.