Home > database >  DJANGO Supplement to the data list via an intermediate table
DJANGO Supplement to the data list via an intermediate table

Time:05-11

I have an intermediate models connection

Simplified:

class Person(models.Model):
      first_name = models.CharField(max_length=20)
      last_name = models.CharField(max_length=20)
      etc...
                
class Company(models.Model):
      name = models.CharField(max_length=60)
      etc...
        
class CompanyEnrollment(models.Model):
      person = models.ForeignKey(Person, on_delete=models.CASCADE)
      company = models.ForeignKey(Company, on_delete=models.CASCADE)
      company_position = 
      models.ForeignKey(CompanyPosition,on_delete=models.CASCADE)
      etc...
      
      class Meta:
            unique_together = [['person', 'company']]
    
class CompanyPosition(models.Model):
      name = models.CharField(max_length=60)

I want to create the following array:

datas = Person.objects.All(...{All elements of Person model supplemented with CompanyPosition_name}...)

There is a case where a person does not have a company_name association Is it possible to solve this with a query?

CodePudding user response:

If you have an explicit through model for your many-to-many relationship, you could use this to only get or exclude based on the entries of this table, using an Exists clause:

enrollments = CompanyEnrollment.objects.filter(person_id=OuterRef('pk'))
enrolled_persons = Person.objects.filter(Exists(enrollments))
unenrolled_persons = Person.objects.filter(~Exists(enrollments))

If you don't have an explicit intermediate table, then it's has been generated by Django directly. You should be able to use it by referring to it with Person.enrollments.through instead of CompanyEnrollment.

Since you did not detailed much the CompanyEnrollment table, I assumed you're in the second case.

CodePudding user response:

This is not the best solution in my opinion, but it works for now, with little data. I think this is a slow solution for a lot of data.

views.py I will compile the two necessary dictionaries

 datas = Person.objects.all().order_by('last_name', 'first_name')
 companys = CompanyEnrollment.objects.all()

Use Paginator

p = Paginator(Person.objects.all(), 20)
page = request.GET.get('page')
pig = p.get_page(page)
pages = "p" * pig.paginator.num_pages

Render HTML:

context = {
        "datas": datas,
        "pig": pig,
        "pages": pages,
        "companys": companys,

    }
    return render(request, "XY.html", context)

HTML template:

{% for datas in pig %}
   {{datas.first_name}} {{datas.last_name}}
     {% for company in companys  %} 
          {% if datas == company.person %}
               {{company.company.name}} <br>
          {% endif %}
     {% endfor %}
{% endfor %}

not the most beautiful, but it works ... I would still accept a more elegant solution.

  • Related