Backend Development
Django
Subjective
Oct 03, 2025
What are Django model relationships and how to implement them?
Detailed Explanation
Django model relationships:\n\n**One-to-Many (ForeignKey):**\n```python\nclass Author(models.Model):\n name = models.CharField(max_length=100)\n\nclass Book(models.Model):\n author = models.ForeignKey(Author, on_delete=models.CASCADE)\n```\n\n**Many-to-Many:**\n```python\nclass Book(models.Model):\n authors = models.ManyToManyField(Author)\n```\n\n**One-to-One:**\n```python\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n```\n\n**on_delete options:**\n• CASCADE - Delete related objects\n• PROTECT - Prevent deletion\n• SET_NULL - Set to NULL\n• SET_DEFAULT - Set to default value
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts