Kevin
Kevin

Reputation: 2257

How to reverse link foreign key in Django model?

Here is my model

class Comment (models.Model):
    parent = models.ForeignKey('Comment',
                           related_name='children',
                           null=True)
    text = models.TextField(blank=True)

    def __repr__(self):
        return self.text

class Thread(models.Model):
    comment = models.ForeignKey('Comment', related_name='parent_thread', null=True)
    text = models.TextField(blank=True)

    def __repr__(self):
        return self.text

When I try to set the thread's comment to a comment instance the comment doesn't get reversed linked (I cannot access the related_name field from comment instance)

from tree.models import Comment, Thread
thread1 = Thread(text='thread1')
c1 = Comment(text='c1')
c1.save()
thread1.save()
thread1.comment = c1
thread1.save()
str(c1.parent_thread) # return None

Why is this happening? Can someone help me out?

Thanks

Upvotes: 0

Views: 733

Answers (1)

Selcuk
Selcuk

Reputation: 59228

You are doing it backwards. If you want to have a parent_thread, you have to put the ForeignKey into the Comment class, not vice versa like this:

class Thread(models.Model):
    ...

class Comment (models.Model):
    parent_thread = models.ForeignKey(Thread)
    ...

In your current code you have multiple Thread objects linked to a single Comment object.

Upvotes: 1

Related Questions