OneToMany Relationship Django.How

Author avatar wrote on 08/06/2022

To define a many-to-one relationship, use ForeignKey:
If a model has a ForeignKey, instances of that model will have access to the related (foreign) object via an attribute of the model.


from django.db import models

class Skill(models.Model):
    name = models.CharField(max_length=256)

    def __str__(self):
        return  self.name


class Subskill(models.Model):
    skill = models.ForeignKey(Skill, on_delete=models.CASCADE)
    name = models.CharField(max_length=256)

    def __str__(self):
        return self.name

View

def home(request):        
    skills = Skill.objects.all().prefetch_related('subskill_set') # optimizing
    context = {'skills':skills}
    return render(request, 'skill.html', context)

In template

{% for skill in skills %}
    {{skill.name}}
    {% for subskill in skill.subskill_set.all %}
        {{subskill.name}}
    {% endfor %}
{% endfor %}

Get by order

sample_object.users_set.all()[0]
# in template
{{ sample_object.users_set.all.0 }}



# another example in template
# TranstorPrice has Translator fk
{% for price in translator.translatorprice_set.all %} 
    

{{price}}

{% endfor %}

Following relationships “backward”

b = Blog.objects.get(id=1)
b.entry_set.all() # Returns all Entry objects related to Blog.

Filter

class Car(models.Model):
    name = models.CharField(max_length=255)

class CarModel(models.Model):
    name = models.CharField(max_length=255)
    car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True)


mercedes.carmodel_set.all()
mercedes.carmodel_set.first()
mercedes.carmodel_set.first().name

Filter car_models by car:

CarModel.objects.filter(car__name="Mercedes")

Filter cars by car_models:

Car.objects.filter(carmodel__name="C180")

Translator has many prices

filtered_prices_by_source = TranslatorPrice.objects.filter(source_language= source_language)
filtered_translators = filtered_translators.filter(translatorprice__in=filtered_prices_by_source).distinct()

Resource
  • https://medium.com/django-rest/one-to-many-relationship-foreignkey-64f8da35912a
  • CRUDgen Django CRUD generator