Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

497
Vistas
Django - get data from foreign key

I'm working on a Django project and attempting to create some linked models for my data which In think is working, but I cannot seem to work out how to access the linked data.

class One(models.Model)
  name = models.CharField(max_length=50)
  list = models.ArrayField(models.CharField(max_length=50), blank=True)

  def __str__(self): 
    return self.name

class Many(models.Model)
  name = models.CharField(max_length=50)

  related = models.ForeignKey(One, null=True, blank=True)

  def __str__(self): 
    return self.name    

This is the general relationship I have set up.

What I am trying to do is, in a template have access to a list of all 'Ones', and via each of those, can access each Many and it's related attributes. I can see how to access the attributes for a single 'One', but not how to pass all of them and their related 'Many' models and the related attributes for each. Essentially the output I'd like would have a drop down list with the One's, and when this is submitted some Javascript will use the list in the 'Many' model to do some stuff.

Any advice would be much appreciated.

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

If you already have the objects of One model class, you can access the many objects using many_set (refer: backward relations):

{% for one_obj in one_objs %}
    {% for m_obj in one_obj.many_set.all %}
        # do stuff with m_obj here
    {% endfor %}
{% endfor %}

One important thing to note here is that this will execute a db query for each m_obj. To make this efficient, you could prefetch the many_set with one_objs in your view.

In your view, use prefetch_related:

one_objs = One.objects.all().prefetch_related('many_set')
about 4 years ago · Santiago Trujillo Denunciar

0

Reverse lookups are accessible through an object's ___set attribte. So to get all the "Many" objects for a given "One" you could do one.many_set

Django reverse lookup of foreign keys

Regarding usage in a template, sets are accessible by adding "all" (since the set returns a queryset, you can run queries against it, including in the template)

Access ForeignKey set directly in template in Django

See the relevant section of the Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

about 4 years ago · Santiago Trujillo Denunciar

0

You can use Django's "prefetch_related" and Django's "related_name".

Also, this question has been answered here.

Though, here is what you might want, first, change your foreign key definition to this :

related = models.ForeignKey(One, null=True, blank=True, related_name='relateds')

Then you can reverse-fetch the foreign keys:

one = One.objects.get(name="TheOneYouWant").prefetch_related('relateds')
manys = one.relateds
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda