Search code examples
djangoforeign-keys

How does one count a foreign key item, esp 'author' created with Django's User model?


Need help getting a better grip with 1) accessing and counting foreign key items in Django and 2) counting foreign key item that is created through Django's built-in User:

#1) The answer here suggests using Django's annotate function: eg. questions = Question.objects.annotate(number_of_answers=Count('answer')) (question being a foreign key item to answer). But it is not clear to me where this line belongs to (in the case of the example, question or answer), or which part of an app-models.py or views.py. I tested in both models.py and views.py

Here are my models (only the essential lines here):

class Post(models.Model):
            post = models.TextField(max_length=1000)
            author = models.ForeignKey(User, related_name="author", on_delete=models.CASCADE)

class Comment(models.Model):
    comment = models.TextField(max_length=1000)
    commenter = models.ForeignKey(User, on_delete=models.CASCADE)
    post_connected =  models.ForeignKey(Post, related_name='posts', on_delete=models.CASCADE, default=None, null=True)

#2) How does one count a foreign key item created using Django's built-in model, User? Should I have created a model called "Author" first?


Solution

  • I want to tell you something about related_name: related_name help you access objects of another model for example

    class Post(models.Model):
        post = models.TextField(max_length=1000)
        author = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE)
    
    class Comment(models.Model):
        comment = models.TextField(max_length=1000)
        commenter = models.ForeignKey(User, on_delete=models.CASCADE)
        post_connected =  models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, default=None, null=True)
    

    with modelobject.related_name.all() get objects of another models in this example userobject.posts.all() you can get all post related to user object. and with post.comments.all() can get all comments related to the post.