我的项目涉及对许多图像进行排序。作为此排序的一部分,我希望能够手动(作为用户)将多个图像标记为彼此重复,并简要说明创建每个关系的原因。这些关系不会在图像加载到 Django 时定义,而是在上传所有图像后的稍后时间定义。
我的问题:如何创建无限数量的副本
?也就是说,我如何定义几个图像都相互关联,并且包括一个CharField
描述为什么每个关系存在?
这是一个 django 应用程序,代码来自 models.py
。
谢谢。
from django.db import models
class tag(models.Model):
tag = models.CharField(max_length=60)
x = models.IntegerField(null=True)
y = models.IntegerField(null=True)
point = [x,y]
def __unicode__(self):
return self.tag
#...
class image(models.Model):
image = models.ImageField(upload_to='directory/')
title = models.CharField(max_length=60, blank=True, help_text="Descriptive image title")
tags = models.ManyToManyField(tag, blank=True, help_text="Searchable Keywords")
#...
##### HELP NEEDED HERE ##################
duplicates = [models.ManyToManyField('self', null=True), models.CharField(max_length=60)]
##########################################
def __unicode__(self):
return self.image.name
最佳答案
您必须使用额外的模型来对这些重复项进行分组,因为您需要一个描述字段。有点像
class DupeSeries(Model):
description = CharField(...)
members = ManyToManyField("image", related_name="dupes", ...)
示例用法:
img = image(title="foo!", image="/path/to/image.jpg")
dup_of_img = image(title="foo!dup", image="/path/to/dup/image.jpg")
img.save()
dup_of_img.save()
dupes_of_foo = DupeSeries(description="foo! lookalikes")
dupes_of_foo.members.add(img, dup_of_img)
# Notice how *img.dupes.all()* returns both image instances.
assert(list(img.dupes.all()) == [img, dup_of_img])
关于python - 递归关系与 Django 模型中的描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17658729/