title: Many-To-Many reverse field lookup with ids in Django | Polymorphic Model
body: <p>I try to figure out how to produce the correct queryset to retrieve</p>
  
  <p><strong>url and value fields</strong> (Attr_1 and Attr_2 model) </p>
  
  <p>from querying the <strong>Object1</strong> models 'reverse set' Many-to-Many Relation. Here is my Example:</p>
  
  <p>models.py:</p>
  
  <pre><code>class Text(models.Model):
      string = models.TextField()
  
  #Entity
  class Element(models.Model):
      pageline = models.IntegerField()
  
  class Object1(Element):
      text = models.ManyToManyField(Text)
  
  class Object2(Element):
      another_var = models.ManyToManyField(Text)
      yet_another = models.CharField(max_length=1)
  
  #Entity
  class Attribute(models.Model):
      belongsTo = models.ManyToManyField(Element)
  
  class Attr_1(Attribute):
      url = models.URLField()
  
  class Attr_2(Attribute):
      value = models.CharField(max_length=255)
      date = models.URLField()
  </code></pre>
  
  <p>If I use:</p>
  
  <pre><code>&gt;&gt; models.Object1.objects.get(pk=1).attribute_set.all()                                                                    
  &lt;QuerySet [&lt;Attribute: Attribute object (1)&gt;, &lt;Attribute: Attribute object (2)&gt;]&gt;
  
  &gt;&gt; models.Object1.objects.get(pk=1).attribute_set.values()                                                                 
  &lt;QuerySet [{'id': 1}, {'id': 2}]&gt;
  </code></pre>
  
  <p>I guess now I have to query Attr_1 for pk=1 and Attr_2 for pk=2? </p>
  
  <p>Does the Attribute model has a relation to know if id=1 is in Attr_1 or Attr_2 model?</p>
  
  <p>Any help is appreciated. Thank you!</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I wonder if a solution is achivieable by using contenttypes:
  <a href="https://stackoverflow.com/questions/33528098/django-model-one-foreign-key-to-many-tables">Django model one foreign key to many tables</a> I have to read and understand the technique.</p>
  
  <p>It seems to me that <a href="https://django-polymorphic.readthedocs.io/en/stable/index.html" rel="nofollow noreferrer">django-polymorphic</a> suits my needs.
  Even though I don't like to use non-buildin libs and would love to know a solution by build in modules. I have no knowledge by hand to build a efficient queryset. Maybe my modeling is wrong?</p>
  
  <p>But with polymorphic model i can query:</p>
  
  <pre><code>&gt;&gt; models.Object1.objects.get(pk=1).attribute_set.all()[0].url                                                                                      
  'http://www.dot.com'
  </code></pre>
  
  <p>I just need to catch the type of object to not run into:</p>
  
  <pre><code>AttributeError: 'Attribute' object has no attribute 'url'
  </code></pre>
  
  <p>Hope somebody can help or explain the topic further even so I found something that works for me.</p>