通过模型通过过滤器获取所有相关对象



我有下一个数据库结构:

class Artwork():
id = models.IntegerField(_('id'), primary_key=True)
artists = models.ManyToManyField('gql_service.Artist',
through='gql_service.ArtistArtwork')
class ArtistArtwork(models.Model): 
artist = models.ForeignKey('gql_service.Artist')
artwork = models.ForeignKey('gql_service.Artwork')
is_main_artist = models.BooleanField(default=False)
class Artist(models.Model):
id = models.IntegerField(_('id'), primary_key=True)

is_main_artist特征标志用于定义此美工的美工主。
ArtworkNode中,我想定义main_artist字段:

class ArtworkNode(PrimaryKeyMixin, DjangoObjectType):
main_artist = graphene.Field('escher.gql_service.schema.artist_node.ArtistNode')
def resolve_main_artist(self, _):
return ArtworkInfo(self).main_artist

然后在ArtworkService中,我可以访问艺术品艺术家,如:

class ArtworkInfo(object):
@property
def main_artist(self):
artist = self.artwork.artists.first()
return artist

是否有任何方法可以在ArtworkInfo上过滤艺术家,并在ArtistArtwork模型中只获得一个主要艺术家或访问值?

可以使用相关名称:

class ArtistArtwork(models.Model): 
...
artwork = models.ForeignKey('gql_service.Artwork', related_name='artwork_artistartwork')

ArtworkService

class ArtworkInfo(object):
@property
def main_artist(self):
artist = self.artwork.objects.filter(artwork_artistartwork__is_main_artist=True).first()
return artist

作为:

@property
def main_artist(self):
return self.artwork.artists.filter(
artistartwork__is_main_artist=True
).first()

相关内容

  • 没有找到相关文章

最新更新