Using Tag model to create ManytoMany relationship
I am trying to fetch data where the column value "tag" belongs to list from the table "UserBookmark".
UserBookmark.objects.filter(tag__in = ['Java','Android'])
but this returns QuerySet[](null set) whereas I do have data matching this query in table
<QuerySet [<UserBookmark: 21 user12 http://careers.bankofamerica.com/ [u'Java']>,<UserBookmark: 22 user12 http://aehlke.github.io/tag-it/examples.html [u'Data Science,Python']>,<UserBookmark: 23 user13 https://github.com/Azure/azure-quickstart-templates [u'Android']>, <UserBookmark: 24 user14 https://github.com/sunnykrGupta/Bigquery-series [u'Python']>, <UserBookmark: 25 user14 https://github.com/ctfs/write-ups-2017 [u'Data Analytics']>]>
models.py
class UserBookmark(models.Model):
user = models.ForeignKey(User)
bookmark = models.URLField()
tag = models.CharField(max_length = 100)
def __str__(self):
return '%i %s %s %s'%(self.id,self.user,self.bookmark,self.tag)
i have modified my models.py
class UserBookmark(models.Model):
user = models.ForeignKey(User)
bookmark = models.URLField()
tags = models.ManyToManyField('Tag',blank=True)
def __str__(self):
return '%i %s %s'%(self.id,self.user,self.bookmark)
class Tag(models.Model):
name = models.CharField(max_length=100, unique=True)
But when i run python manae.py migrate after python managepy makemigrations, I get this error:
ValueError: Cannot alter field bookmark.UserBookmark.tags into bookmark.UserBookmark.tags - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)
What am i doing wrong here?
The problem is not in your query, but in the way you are storing your data. You have a single CharField, and you seem to be populating it by simply converting a list to a string. So your records contain for example the literal string "[u'Data Science,Python']"
.
If you want to store this kind of tag, you need to store the tags separately. One way to do this would be to set up a separate Tag model and use a many-to-many relationship. There are various third-party packages that do this for you - one example is django-taggit.
尝试复数化,也许使用tags__in
下一篇: 使用标签模型创建ManytoMany关系