如何将用户模型与分类模型链接。如何为特定用户添加术语以及如何检索它们?
我对Django很陌生,所以你必须原谅我缺乏知识,而不是掌握具体的术语。
我有以下模型,扩展了基本用户:
class UserProfile(models.Model):
user = models.OneToOneField(User)
birthday = models.DateField(blank=True)
about_me = models.TextField(blank=True,null=True)
avatar = models.ForeignKey(Picture,blank=True, null=True)
class Meta:
db_table = 'auth_user_profile'
我还有以下分类模型:
class TaxonomyGroup(models.Model):
related taxonomy items"""
name = models.CharField(max_length=25, db_index=True)
slug = AutoSlugField(populate_from='name', unique = True)
def __unicode__(self):
return u'%s' %self.name
class Meta:
db_table = 'taxonomies'
ordering = ['name']
class TaxonomyItem(models.Model):
taxonomy_group = models.ForeignKey(TaxonomyGroup, db_index=True)
name = models.CharField(max_length=55, db_index=True)
slug = AutoSlugField(populate_from='name', unique = True)
def __unicode__(self):
return u'%s' %self.name
class TaxonomyMap(models.Model):
taxonomy_group = models.ForeignKey(TaxonomyGroup, db_index=True)
taxonomy_item = models.ForeignKey(TaxonomyItem, db_index=True)
content_type = models.ForeignKey(ContentType, db_index=True)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type','object_id')
objects = TaxonomyManager()
class Meta:
db_table = 'term2object'
unique_together = ('taxonomy_item', 'content_type', 'object_id')
答案 0 :(得分:0)
我看到它的方式,你想要分类法和用户模型之间的多对多关系,所以你可以将它添加到UserProfile模型。
class UserProfile(models.Model):
user = models.OneToOneField(User)
birthday = models.DateField(blank=True)
about_me = models.TextField(blank=True,null=True)
avatar = models.ForeignKey(Picture,blank=True, null=True)
taxonomies = models.ManyToManyField(TaxonomyItem)
然后,当您为特定用户添加术语时,您将执行以下操作:
taxonomy = TaxonomyItem.objects.create(taxonomy_group=<some_group>, name=<some_name>,...)
profile = user.get_profile()
profile.taxonomies.add(taxonomy)
检索你可以做到
profile.taxonomies.all()