我有下一个数据库结构:
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()