Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - get data from foreign key

Tags:

python

django

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.

like image 796
Nowandthen98 Avatar asked Sep 10 '25 17:09

Nowandthen98


2 Answers

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')
like image 181
AKS Avatar answered Sep 13 '25 08:09

AKS


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
like image 41
Qrom Avatar answered Sep 13 '25 08:09

Qrom