将对象移动到继承的模型

时间:2014-05-22 14:55:59

标签: python django django-models

我有一个模型,用于存储从办公室的群聊室中删除的网址,我希望能够根据网址将对象移动到继承的模型。我知道继承的字段只是一个OneToOne关系,是否有一种简单的方法将对象转换为继承的模型?以下是有问题的模型:

class Link(models.Model):
    url = models.URLField(max_length=2048, unique=True)
    message = models.TextField()
    room = models.ForeignKey(Room)
    posted = models.DateTimeField()

    def save(self, *args, **kwargs):
        image_types = ['gif', 'jpg', 'jpeg', 'ico', 'png'. 'tiff', 'bmp']
        if self.url.split('.')[-1] in image_types:
             convert to ImageLink
        super(Link, self).save(*args, **kwargs)

class ImageLink(Link):
    pass

1 个答案:

答案 0 :(得分:0)

image_link = models.ImageLink.objects.create(url='http://example.com')
print(image_link.link_ptr.url) #http://example.com
#When we create image_link instance we create image instance implicitly 

link = models.Link.objects.create(url='http://example1.com')
image_link = models.ImageLink.objects.create(link_ptr=link, url=link.url)
"""
To create image_link from link we can use such approach. It won't actually convert link into image_link
since it's impossible for image_link to exist without link.
"""
print(image_link.url) #http://example1.com