Django:如何在类中添加模型类或引用? [英] Django: How to add model class inside class or refer?
问题描述
我有一个叫做Artist的类,它是一个艺术家的个人资料
I have a class called artist which is a profil for an artist
class Artist_object(models.Model):
surname = models.CharField(max_length=120)
name = models.CharField(max_length=120)
Biography = models.TextField(default='Bitte Biography eingfügen', null=False)
现在,我希望这位艺术家可以创作多幅带有破坏性的画作.
now I want that this artist can have multiple paintings with a desrciption.
class Artist_painting(models.Model):
painting1 = models.ImageField()
painting1_desc = models.CharField(max_length=120, default=None)
painting2 = models.ImageField()
painting2_desc = models.CharField(max_length=120, default=None)
如何将类Artist_painting放到我查看的每个艺术家的Artist_object中(我得到了 def get_absolute_url(self):返回f'/artist/{self.id}'
)上有每张图片的描述?
How can I put class Artist_painting inside the Artist_object that for every artist I view (i got
def get_absolute_url(self): return f'/artist/{self.id}'
) it have an description for every image ?
推荐答案
这是一个关系, ManyToOne
,每个 Artist
有很多 Painting
>, ManyToOne
关系称为 ForiegnKey
,因为 Artist
本身是 Painting
的键,每个绘画
只有一名 Artist
.
This is a relation, ManyToOne
, Many Painting
s for each Artist
, ManyToOne
relation is called ForiegnKey
because the Artist
himself is a key to the Painting
, Each Painting
has only one Artist
.
class Artist(models.Model):
"""
no need to call it Artist_object, Stick with pep8 (ArtistObject)
or better yet, Artist only because it's an object anyways.
"""
surname = models.CharField(max_length=120)
name = models.CharField(max_length=120)
Biography = models.TextField(default='Bitte Biography eingfügen', null=False)
class Painting(models.Model):
"""
Same naming rules apply
"""
artist = models.ForiegnKey(Artist, on_delete=models.CASCASE, related_name="paintings")
-
相关名称是什么?
What's the related name?
artist
是一个类变量,通过使用painting_instance.artist
从Painting
实例调用artist
变量>,如果我们想获取与艺术家相关的Painting
,那是通过使用artist_instance.related_name
,在这种情况下是artist_instance.paintings
,如果您未指定related_name
,则默认为painting_qs
,如果您不想访问反向关系
,我的意思是.paintings
,请使用related_name ="+"
artist
is a class variable, Calling theartist
variable from aPainting
instance is by usingpainting_instance.artist
, What if we wanted to get thePainting
s associated with an artist, It's by usingartist_instance.related_name
and in this case, It'sartist_instance.paintings
, If you didn't specify arelated_name
, It will bepainting_qs
by default, If you don't want to have access to thereverse relation
, I mean the.paintings
, Userelated_name="+"
什么是
CASCASE
?这是一个基本的SQL短语,这意味着当
Artist
被删除时,也要删除其Painting
s.It's a basic SQL phrase which means, when the
Artist
gets deleted, delete hisPainting
s too.请参考此答案获取有关
ForiegnKey
这篇关于Django:如何在类中添加模型类或引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!