Search code examples
djangodjango-modelsmodelforeign-keysone-to-one

How to connect django model using foreignkey to a unique object in another model


Please how do I connect a model to a particular object in another model using either onetoonefield or foreignkey.

Example

class Post(models.Model):
    title = models.TextField(max_length=100, null=True)
    caption = models.CharField(max_length=1000)
    photo = models.ImageField(upload_to ='posts', null=True)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    likes= models.IntegerField(default=0)
    dislikes= models.IntegerField(default=0)
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True)
    digital = models.BooleanField(default=False, null=True, blank=False)
    location = models.PointField(srid=4326, null=True)
    category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, null=True)

    def __str__(self):
        return self.title

    @property
    def number_of_comments(self):
        return Comment.objects.filter(post_connected=self).count()


class Comment(models.Model):
    **post_owner = models.OneToOneField(      )** 
    content = models.TextField(max_length=150)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post_connected = models.ForeignKey(Post, on_delete=models.CASCADE)

I need to make post_owner in Comment Models, connected to author in Post models and not the entire Post models


Solution

  • assuming you have a comment object you can access its owner using something like this.

    comment = Comment.objects.first()
    owner = comment.post_connected.author