Search code examples
pythondjangodjango-modelsone-to-oneassociated-object

How to get the associated data of `OneToOneField()` in Django?


I'm working in Django 2.0

I have a model Note to save note and two another models to add color labels to the note.

class Note(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=250, blank=True, default='Untitled')
    content = models.TextField(blank=True)

class ColorLabels(models.Model):
    title = models.CharField(max_length=100, unique=True)
    value = models.CharField(max_length=100)
    default = models.BooleanField(default=False)

class NoteLabel(models.Model):
    note = models.OneToOneField(Note, on_delete=models.CASCADE)
    color_label = models.OneToOneField(ColorLabels, on_delete=models.CASCADE)

with the object of Note

note = Note.objects.get(pk=1)

I want to access associated ColorLabels's title and value fields or the NoteLabel object.

since they are one to one field. I tried doing

note.note_label
note.NoteLabel
note.note_label_set

But all returns error as

AttributeError: 'Note' object has no attribute 'note_label_set'

Solution

  • Unless you define related_name in your OneToOneField, Django will use lowercased model name to access related object. So, note.notelabel should work.