2013-07-15 41 views
1

我的項目涉及排序許多圖像。作爲這種排序的一部分,我希望能夠手動(作爲用戶)將多個圖像標記爲彼此的副本,並簡要說明爲什麼創建每個關係。這些關係不會在圖像加載到Django時定義,但在上載所有圖像後的較晚時間。與Django模型中的描述的遞歸關係

我的問題:我如何創建無限數量的duplicates?也就是說,我如何定義幾個圖像都是相互關聯的,包括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 
+1

聽起來像你將使用帶有許多一對多的關係。您還可以設置自定義的「通過」模型,以允許您添加描述等字段。 https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships – Ngenator

回答

1

你必須去一個額外的模型來分組這些重複,因爲你想要一個描述字段。喜歡的東西

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]) 
+0

由於我對此很新,你能解釋這將如何鏈接兩個圖像在一起,以及這是否允許我調用'image.duplicates'來列出所有其他相關圖像?您可能會建議一種更好的方法,但我並不十分注意... – mh00h

+0

又名,它似乎就像你在暗示這一點(https://docs.djangoproject.com/en/1.5/topics/db/models/#外地多對多關係),但我真的不明白你要去哪裏。 – mh00h

+0

請查看我的編輯。我認爲這比使用'through'的解決方案更易於使用和理解,但如果您需要它,我也可以編輯以展示'through'方法。 – XORcist