简体   繁体   English

Django - 创建模型的子模型

[英]Django - create submodels of a model

I want to create submodels(I do not know if this is the correct term to use) of a model.我想创建模型的子模型(我不知道这是否是正确的术语)。 For example, let's say I have a model called Post .例如,假设我有一个名为Post的模型。 But I want this model's fields changable by users.但我希望用户可以更改此模型的字段。 Like users select their Post type.喜欢的用户选择他们的Post类型。 Right now I want to create a two different types: first is a现在我想创建两个不同的类型:第一个是

class TextBasedPost(models.Model):
    title = models.CharField(max_length=100)
    content = RichTextField() # which has been imported from ckeditor.fields
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    datePosted = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post_detail',kwargs={'pk':self.pk})

Other one is a post with only image attachment:另一个是只有图片附件的帖子:

class ImageBasedPost(models.Model):
    title = models.CharField(max_length=100)
    image_attachment = models.ImageField(default='default.png', upload_to='profile_pics') # there will not be a usage of default.png
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    datePosted = models.DateTimeField(default=timezone.now)

    def crop_image(self):
        img = Image.open(self.image.path) # Image imported from PIL

        if img.height > 600 or img.width > 600:
            output_size = (600,600)
            img.thumbnail(output_size)
            img.save(self.image_attachment.path)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post_detail',kwargs={'pk':self.pk})

But like you see this is not good way to use since there are same fields and same functions in both models(only one fields and one function is different).但是就像您看到的那样,这不是一个好的使用方法,因为两个模型中有相同的字段和相同的功能(只有一个字段和一个功能不同)。 But this is not a good practice.但这不是一个好习惯。 So is there a way to do this with better way?那么有没有办法以更好的方式做到这一点?

the best approach is to create an abstract parent model and put all shared fields inside of it.最好的方法是创建一个抽象的父模型并将所有共享字段放入其中。 then inherit your models from it, and add the fields you wants to any of them.然后从中继承您的模型,并将您想要的字段添加到其中任何一个。 you will then be able to override your methods inside the child models:然后,您将能够在子模型中覆盖您的方法:

class GenericPost(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    datePosted = models.DateTimeField(default=timezone.now)


    class Meta:
        abstract = True

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post_detail',kwargs={'pk':self.pk})

class TextBasedPost(GenericPost):
    content = RichTextField() # which has been imported from ckeditor.fields
    
class ImageBasedPost(GenericPost):
    image_attachment = models.ImageField(default='default.png', upload_to='profile_pics') # there will not be a usage of default.png

    def crop_image(self):
        img = Image.open(self.image.path) # Image imported from PIL

        if img.height > 600 or img.width > 600:
            output_size = (600,600)
            img.thumbnail(output_size)
            img.save(self.image_attachment.path)

learn more here: https://docs.djangoproject.com/en/3.1/topics/db/models/#abstract-base-classes在此处了解更多信息: https : //docs.djangoproject.com/en/3.1/topics/db/models/#abstract-base-classes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM