I try to figure out how to produce the correct queryset to retrieve
url and value fields (Attr_1 and Attr_2 model)
from querying the Object1 models 'reverse set' Many-to-Many Relation. Here is my Example:
models.py:
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()
If I use:
>> models.Object1.objects.get(pk=1).attribute_set.all()
<QuerySet [<Attribute: Attribute object (1)>, <Attribute: Attribute object (2)>]>
>> models.Object1.objects.get(pk=1).attribute_set.values()
<QuerySet [{'id': 1}, {'id': 2}]>
I guess now I have to query Attr_1 for pk=1 and Attr_2 for pk=2?
Does the Attribute model has a relation to know if id=1 is in Attr_1 or Attr_2 model?
Any help is appreciated. Thank you!
EDIT:
I wonder if a solution is achivieable by using contenttypes: Django model one foreign key to many tables I have to read and understand the technique.
It seems to me that django-polymorphic 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?
But with polymorphic model i can query:
>> models.Object1.objects.get(pk=1).attribute_set.all()[0].url
'http://www.dot.com'
I just need to catch the type of object to not run into:
AttributeError: 'Attribute' object has no attribute 'url'
Hope somebody can help or explain the topic further even so I found something that works for me.