0

如何将用户模型与分类模型链接。如何为特定用户添加术语以及如何检索它们?

我对 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')
4

1 回答 1

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()
于 2013-02-15T17:37:51.333 回答