AttributeError: объект 'QuerySet' не имеет атрибута 'tags' при попытке сохранить кавычки и теги с помощью ClusterableModel и ClusterTaggableManager
Я пытаюсь сохранить некоторые цитаты из файла csv в мою модель django с помощью python manage.py shell
, потому что я не смог использовать django-import-export для этого. Я спрашивал об этом на Tags imported but relationship not imported with django-import-export, но никто не ответил, и я не смог найти больше вещей, которые можно попробовать, погуглив.
После прочтения документации и предыдущих ответов здесь о django querysets и тегах, мне удалось сохранить большую часть каждой цитаты, но теги не сохраняются. Набор запросов не возвращает поле tags
, что вызывает ошибку AttributeError. Пожалуйста, посмотрите вывод оболочки q: <QuerySet...
ниже
Моя модель тегов следует https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models.
Из django-admin отношения работают. Итак, недостающий фрагмент головоломки - сохранение тегов.
Какой запрос я должен использовать для нахождения поля tags или какой метод я должен использовать для сохранения тегов?
#Сценарий, который я пытаюсь запустить в python manage.py shell
import csv
from quotes.models import Quote, TaggedQuote
with open("test_import1.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
if row["book"]:
item = Quote(
text=row["text"],
author=row["author"],
source_url=row["url"],
book=row["book"],
)
elif not row["book"]:
item = Quote(text=row["text"], author=row["author"], source_url=row["url"])
item.save()
for each in row["tags"].split(", "):
each = str(each).strip("'")
q = Quote.objects.filter(text__exact=row["text"].strip('"')).values()
print(f"each: {each}")
print(f"q: {q}")
q.tags.add(each)
Вывод оболочки
each: attributednosource
q: <QuerySet [{'id': 56, 'text': "I'm selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle. But if you can't handle me at my worst, then you sure as hell don't deserve me at my best.", 'author': 'Marilyn Monroe', 'book': '', 'book_url': '', 'source_url': 'https://www.goodreads.com/quotes/tag/love', 'user_id': None, 'imported': True, 'created': datetime.datetime(2021, 9, 1, 9, 53, 25, 224023, tzinfo=<UTC>), 'updated': datetime.datetime(2021, 9, 1, 9, 53, 25, 224084, tzinfo=<UTC>), 'active': True, 'inactive_message': ''}]>
Traceback (most recent call last):
File "<console>", line 26, in <module>
AttributeError: 'QuerySet' object has no attribute 'tags'
models.py
test_import1.csv
,text,author,tags,url,book
0,"I'm selfish, impatient and a little insecure. I make mistakes, I am out of control and at times hard to handle. But if you can't handle me at my worst, then you sure as hell don't deserve me at my best.",Marilyn Monroe,"attributednosource, best, life, love, mistakes, outofcontrol, truth, worst",https://www.goodreads.com/quotes/tag/love,
1,"You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth.",William W. Purkey,"dance, heaven, hurt, inspirational, life, love, sing",https://www.goodreads.com/quotes/tag/love,
2,You know you're in love when you can't fall asleep because reality is finally better than your dreams.,Dr. Seuss,"attributednosource, dreams, love, reality, sleep",https://www.goodreads.com/quotes/tag/love,
3,A friend is someone who knows all about you and still loves you.,Elbert Hubbard,"friend, friendship, knowledge, love",https://www.goodreads.com/quotes/tag/love,
4,Darkness cannot drive out darkness: only light can do that. Hate cannot drive out hate: only love can do that.,Martin Luther King Jr.,"darkness, driveout, hate, inspirational, light, love, peace",https://www.goodreads.com/quotes/tag/love,A Testament of Hope: The Essential Writings and Speeches
5,We accept the love we think we deserve.,Stephen Chbosky,"inspirational, love",https://www.goodreads.com/quotes/tag/love,The Perks of Being a Wallflower
Использование Quote.objects.get(text__exact=row["text"].strip('"'))
работает. Я ожидал, что Quote.objects.filter(text__exact=row["text"].strip('"'))
вернет 1 результат и думал, что это должно сработать, но я ошибся.
Я протестировал это в python manage.py shell
и это сработало.
import csv
from quotes.models import Quote
with open("test_import1.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
# Check if quote exists
if Quote.objects.filter(text__exact=row["text"].strip('"')):
print(f"Not added because it already exists: {row['text']}")
else:
if row["book"]:
item = Quote(
text=row["text"],
author=row["author"],
source_url=row["url"],
book=row["book"],
)
elif not row["book"]:
item = Quote(text=row["text"], author=row["author"], source_url=row["url"])
item.save()
for each in row["tags"].split(", "):
each = str(each).strip("'")
q = Quote.objects.get(text__exact=row["text"].strip('"'))
q.tags.add(each)
q.save()
В q.tags.add(each)
, q
является списком объектов, поэтому вы не можете использовать tag
напрямую.
Либо перебрать все объекты цитаты:
for q in Quote.objects.filter(text__exact=row["text"].strip('"')):
q.tags.add(each)
или получить один объект через get
:
q = Quote.objects.get(text__exact=row["text"].strip('"'))
q.tags.add(each)
или фильтровать, но возвращать один объект, например, используя first
:
q = Quote.objects.filter(text__exact=row["text"].strip('"')).first()
q.tags.add(each)