Home > OS >  Django - Can not join 2 models
Django - Can not join 2 models

Time:01-31

Problem: Joining 2 models in Django.

Error: Error during template rendering. Direct assignment to the reverse side of a many-to-many set is prohibited. Use entity_id.set() instead.

I have read through all the threads on SO. Tried all the suggested solutions, read the Django documentation and think I just must be fundamentally misunderstanding something. Any help would be much appreciated.

I have 2 models. Entity and File.

An Entity can have multiples Files but each File only has 1 Entity.

The primary keys of each table are just auto incrementing integers. Therefore I want to join column entity_id from File with entity_id from Entity. According to the documentation I have set entity_id in File as a ForeignKey. And I have set entity_id as unique in Entity

class Entity(models.Model):
    pk_entity = models.AutoField(primary_key=True)
    entity_id = models.IntegerField(blank=True, null=True, unique=True)  
    name = models.CharField(blank=True, null=True)
    
    class Meta:
        managed = False
        db_table = 'entities'


class File(models.Model):
    pk_file = models.AutoField(primary_key=True)
    filename = models.CharField(blank=True, null=True)    
    entity_id = models.ForeignKey(Entity, on_delete= models.CASCADE, to_field='entity_id')
    

The view is just trying to render this. I have tried using .all() rather than select_related() but no data renders.

class TestListView(ListView):  
    queryset = File.objects.select_related()    
    template_name = "operations/files/test_list.html"

And this is the html:

{% extends "base.html" %}
{% block content %}
<div>
    <div>       
        <ul>
            {% for x in object_list %}
            <li>             
                {{x}} 
             </li>
            {% empty %}
            <p>Empty</p>
            {% endfor %}
        </ul>      
    </div>
</div>
{% endblock %}

CodePudding user response:

When using select_related you should pass your field name to be selected.

Try this:

class TestListView(ListView):  
    queryset = File.objects.select_related("entity").all()    
    template_name = "operations/files/test_list.html"
  • Related