简体   繁体   中英

Retrieve the attribute list of records during querying process

I have model table so Tag and Article,

class Tag(models.Model):
    owner = models.ForeignKey(User,on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    ...
class Article(models.Model):
    tags = models.ManyToManyField(Tag, blank=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    ...

I intent to retrieve the tags of a specified article and convert them to string:

1, Fetch the latest article:

In [26]: articles = Article.objects.all()
In [27]: len(articles)
Out[27]: 41
In [29]: a = articles[40]
In [30]: a 
Out[30]: <Article: Test new tags>

2, get it's tags queryset

In [32]: tags = a.tags.all()
In [32]: tags
Out[32]: <QuerySet [<Tag: python>, <Tag: django>, <Tag: git>, <Tag: javascript>]>

3, convert queryset to a stringset

In [36]: str_tags = ",".join([tag.name for tag in tags])
In [36]: str_tags   
Out[36]: 'python,django,git,javascript'

Could I get the str_tags directly by making an query?

You can use values_list('name', flat=True) :

tag_names = ",".join(a.tags.values_list('name', flat=True))

Aso to get last article just use last() :

a = Article.objects.last()

无需进行两次查询,您可以定义一个类似的东西,因为它的M2M字段ArticleTag = Article.tags.through ,然后可以像标签= ArticleTag.objects.filter(article_id = id)进行查询,然后可以执行str_tags =“,” .join([标签中标签的tag.name])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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