gpt4 book ai didi

python - 将对象移动到继承的模型

转载 作者:行者123 更新时间:2023-11-28 19:21:36 24 4
gpt4 key购买 nike

我有一个模型,用于存储从我们办公室的群聊室中抓取的 URL,我希望能够将对象移动到基于 url 的继承模型。我知道继承字段只是一个 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

最佳答案

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

关于python - 将对象移动到继承的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23810365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com