Code

Ticket #11815: model_inheritance.txt

File model_inheritance.txt, 7.9 KB (added by anonymous, 5 years ago)

Multi-table inheritance

Line 
1
2class Image(models.Model):   
3    description = models.CharField(max_length=500)
4    image = models.ImageField(upload_to='images')
5    image_revision = models.OneToOneField('ImageRevision', primary_key=True)
6    image_static = models.ForeignKey('ImageStatic')
7   
8    class Meta:
9        verbose_name = _(u'Image')
10        verbose_name_plural = _(u'Images')
11        ordering = ['image_revision']
12
13    def __unicode__(self):
14        return self.description
15
16
17class Revision(models.Model):
18    """A report of an older version of some Article."""
19
20    revision_id = models.PositiveIntegerField(_(u"Revision Number"))
21    article_static = models.ForeignKey('ArticleStatic', null=True)
22
23    # Editor identification
24    editor = models.ForeignKey(User, verbose_name=_(u'Editor'), null=True)
25    editor_ip = models.IPAddressField(_(u"IP Address of the Editor"))
26
27    comment = models.CharField(_(u"Editor comment"), max_length=100, blank=True)
28    modified = models.DateTimeField(_(u"Modified at"), default=datetime.now)
29    reverted = models.ForeignKey('self', null=True)
30
31    objects = RevisionManager()
32
33
34class ImageRevision(Revision):
35    """A report of an older version of some Image."""
36    #revision_ptr = models.OneToOneField('Revision',primary_key=True,parent_link=True)
37    image_static = models.ForeignKey('ImageStatic')
38    class Meta:
39        verbose_name = _(u'ImageRevision')
40        verbose_name_plural = _(u'ImageRevisions')
41        get_latest_by  = 'modified'
42        ordering = ('-id',)
43    objects = models.Manager()   
44    rev_manager = ImageRevisionManager()
45    def __unicode__(self):
46        return u'#%s' % self.pk
47
48class ImageStatic(models.Model):
49    """ Image metadata not under change control
50    """
51    creator = models.ForeignKey(User, verbose_name=_('Image Creator'), null=True, related_name='createdimage_set')
52    creator_ip = models.IPAddressField(_("IP Address of the Image Creator"), blank=True, null=True)
53    created_at = models.DateTimeField(default=datetime.now)
54    feature_id = models.PositiveIntegerField(null=True, db_index=True, blank=True)
55    published = models.BooleanField(default=False)
56    project = models.ForeignKey(Project, null=True)
57    source_url = models.URLField(verify_exists=False, null=True)
58    note_text = models.TextField(default="")
59    copy_of = models.ForeignKey("self", null=True, blank=True, related_name='copies') # field to track original copy of an object
60    associator = models.ForeignKey(User, null=True, blank=True)
61
62
63    def latest(self):
64        return self.image_set.order_by('image_revision')[0]
65
66    def first(self):
67        return self.image_set.order_by('-image_revision')[0]
68
69I have used multi table inheritance in the ImageRevision model. What is heppening when I call image static objects's latest or first method getting a sql error.
70
71
72>>> project = get_object_or_404(Project, instance='gw')
73>>> image_static = get_object_or_404(ALL_IMAGES, pk=54, project=project)
74>>> rev = image_static.imagerevision_set.count()
75>>> rev = image_static.image_set.count()
76>>> rev = image_static.image_set.order_by('revision')[0]
77Traceback (most recent call last):
78  File "<console>", line 1, in <module>
79  File "C:\Python25\Lib\site-packages\django\db\models\query.py", line 238, in _
80_getitem__
81    return list(qs)[0]
82  File "C:\Python25\Lib\site-packages\django\db\models\query.py", line 162, in _
83_len__
84    self._result_cache.extend(list(self._iter))
85  File "C:\Python25\Lib\site-packages\django\db\models\query.py", line 275, in i
86terator
87    for row in self.query.results_iter():
88  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 206,
89in results_iter
90    for rows in self.execute_sql(MULTI):
91  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 1724,
92 in execute_sql
93    sql, params = self.as_sql()
94  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 261,
95in as_sql
96    ordering = self.get_ordering()
97  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 656,
98in get_ordering
99    self.model._meta, default_order=asc):
100  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 684,
101in find_ordering_name
102    opts, alias, False)
103  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 1321,
104 in setup_joins
105    "Choices are: %s" % (name, ", ".join(names)))
106FieldError: Cannot resolve keyword 'revision' into field. Choices are: article,
107description, image, image_revision, image_static
108>>> rev = image_static.image_set.order_by('imagerevision')[0]
109Traceback (most recent call last):
110  File "<console>", line 1, in <module>
111  File "C:\Python25\Lib\site-packages\django\db\models\query.py", line 238, in _
112_getitem__
113    return list(qs)[0]
114  File "C:\Python25\Lib\site-packages\django\db\models\query.py", line 162, in _
115_len__
116    self._result_cache.extend(list(self._iter))
117  File "C:\Python25\Lib\site-packages\django\db\models\query.py", line 275, in i
118terator
119    for row in self.query.results_iter():
120  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 206,
121in results_iter
122    for rows in self.execute_sql(MULTI):
123  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 1724,
124 in execute_sql
125    sql, params = self.as_sql()
126  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 261,
127in as_sql
128    ordering = self.get_ordering()
129  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 656,
130in get_ordering
131    self.model._meta, default_order=asc):
132  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 684,
133in find_ordering_name
134    opts, alias, False)
135  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 1321,
136 in setup_joins
137    "Choices are: %s" % (name, ", ".join(names)))
138FieldError: Cannot resolve keyword 'imagerevision' into field. Choices are: arti
139cle, description, image, image_revision, image_static
140>>> rev = image_static.image_set.order_by('image_revision')[0]
141Traceback (most recent call last):
142  File "<console>", line 1, in <module>
143  File "C:\Python25\Lib\site-packages\django\db\models\query.py", line 238, in _
144_getitem__
145    return list(qs)[0]
146  File "C:\Python25\Lib\site-packages\django\db\models\query.py", line 162, in _
147_len__
148    self._result_cache.extend(list(self._iter))
149  File "C:\Python25\Lib\site-packages\django\db\models\query.py", line 275, in i
150terator
151    for row in self.query.results_iter():
152  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 206,
153in results_iter
154    for rows in self.execute_sql(MULTI):
155  File "C:\Python25\Lib\site-packages\django\db\models\sql\query.py", line 1734,
156 in execute_sql
157    cursor.execute(sql, params)
158  File "C:\Python25\Lib\site-packages\django\db\backends\util.py", line 19, in e
159xecute
160    return self.cursor.execute(sql, params)
161  File "C:\Python25\Lib\site-packages\django\db\backends\mysql\base.py", line 83
162, in execute
163    return self.cursor.execute(query, args)
164  File "C:\Python25\lib\site-packages\MySQLdb\cursors.py", line 166, in execute
165    self.errorhandler(self, exc, value)
166  File "C:\Python25\lib\site-packages\MySQLdb\connections.py", line 35, in defau
167lterrorhandler
168    raise errorclass, errorvalue
169OperationalError: (1054, "Unknown column 'cms_imagerevision.revision_ptr_id' in
170'on clause'")
171
172
173I can see from the sql query that it is referring a column which is not in the JOIN statement.
174
175I have printed sql query and it is this one:
176
177SELECT `cms_image`.`description`, `cms_image`.`image`, `cms_image`.`image_revision_id`, `cms_image`.`image_static_id` FROM `cms_image`
178INNER JOIN `cms_revision` ON (`cms_imagerevision`.`revision_ptr_id` = `cms_revision`.`id`) WHERE `cms_image`.`image_static_id` = 54 
179ORDER BY `cms_image`.`image_revision_id` DESC
180
181Same error happens when image objects delete method is called.
182
183