我的 webapp 中有两个 Django 类,Image 和 Tag(请原谅格式),如下所示:
class Image(models.Model):
image_path = models.CharField(max_length=200)
image_name = models.CharField(max_length=200)
x = models.IntegerField(default=0)
y = models.IntegerField(default=0)
num_tags = models.IntegerField(default=0)
image_score = models.FloatField()
def __unicode__(self):
return u'%d' % self.id
class Meta:
unique_together = ("image_path", "image_name")
class Tag(models.Model):
TEXT_BRIGHTNESS_CHOICES = (
('bright', 'bright'),
('dark', 'dark'),
)
image = models.ForeignKey(Image)
tag_text = models.CharField(max_length=200)
x = models.IntegerField(default=0)
y = models.IntegerField(default=0)
width = models.IntegerField(default=0)
height = models.IntegerField(default=0)
textbrightness = models.CharField(max_length=10, choices=TEXT_BRIGHTNESS_CHOICES, default='dark')
text_alignment = models.CharField(max_length=16, default="horizontal")
def __unicode__(self):
return self.tag_text
我想返回对所有 Image 对象的查询,类似于 Image.objects.all(),但是在查询集中,是否也可以获取 Tag.image = Image.id 的所有 Tag 对象?对不起,我敢肯定这在 SQL 中会很容易,但我不知道如何在这里做......
编辑:感谢大家的回复,但是有没有办法让 QuerySet 包含图像信息和与之关联的所有标签?我正在尝试生成包含所有信息的 XML 格式。例子:
<image image_path="downloaded_images/1_music_working/">
<imageName>51rtpUU4meL.jpg</imageName>
<resolution x="393" y="500" />
<taggedRectangles>
#each tag associated with the photo will go here
</taggedRectangles>
</image>
我正在使用 Django 模板来填写信息。模板如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<tagset>
{% for object in query_set %}
<image image_path="{{object.image_path}}">
<imageName>{{object.image_name}}</imageName>
<resolution x="{{object.x}}" y="{{object.y}}" />
<taggedRectangles>
</taggedRectangles>
</image>
{% endfor %}
</tagset>