# Many-to-One Relationships

**Create the `Post` and `Comment` models:**

```

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    text = models.TextField()
    date_created = models.DateTimeField(auto_now_add=True)


```

In this example:

We have two models: Post and Comment. Each Post can have multiple Comment objects associated with it, creating a Many-to-One relationship. The Comment model has a foreign key field post that establishes the relationship to the Post model. The on\_delete=models.CASCADE argument means that if a Post is deleted, all its associated comments will be deleted as well. We also have a text field to store the content of the comment and a date\_created field to store the creation date.

**Create and retrieve Post and Comment objects:**

```python
# Create a new post
post = Post.objects.create(title="Sample Post", content="This is the content of the post.")

# Create comments related to the post
comment1 = Comment.objects.create(post=post, text="First comment on the post.")
comment2 = Comment.objects.create(post=post, text="Second comment on the post.")

# Retrieve comments for a specific post
comments_for_post = Comment.objects.filter(post=post)

# Access the related post for a comment
for comment in comments_for_post:
    print(f"Comment: {comment.text}")
    print(f"Posted on: {comment.date_created}")
    print(f"Related Post: {comment.post.title}\n")

```

We first create a Post and two related Comment objects. Each comment is associated with the post it relates to. We then retrieve all comments related to a specific post using Comment.objects.filter(post=post). To access the related Post for each comment, we use the comment.post attribute, which gives us access to the associated Post object. This example demonstrates a Many-to-One relationship in Django between the Post and Comment models. It allows you to associate multiple comments with a single post and easily access them through the foreign key relationship.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://olee-tech.gitbook.io/django/django-orm/model-relationships-and-related-names/many-to-one-relationships.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
