Tuesday, April 28, 2015

has_many in Django 1.8

In Rails you can create a relationship between the models by has_many and belongs_to. Django has an analog of belongs_to which is ForeignKey but it seems it doesn't have something like has_many. Actually it does:

from django.db import models
class MyModel1(models.Model):
    field1 = models.CharField(max_length=255)
    # has_many MyModel2, implicitly


class MyModel2(models.Model):
    field1 = models.CharField(max_length=255)
    my_model1 = models.ForeignKey(MyModel1) # has_one MyModel1 


my_model1 = MyModel1.object.get(id=1)
my_model1.mymodel2_set.all() # has_many

Pay attention that there's no white-space in mymodel2_set between my and model2_set

No comments :

Post a Comment