0

How do I link the User model with a Taxonomy model. How do add terms for a specific user and how can I retrieve them?

I'm quite new to Django so you must excuse my lack of knowledge and for not grasping the specific terminology, yet.

I have the folowing model witch extends the basic user:

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'

I also have the following taxonomy model:

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')

1 Answers1

0

The way I see it, you want a many-to-many relationship between the taxonomy and user models, so you can add it to UserProfile model.

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)

Then when you are adding terms for a specific user you'll do:

taxonomy = TaxonomyItem.objects.create(taxonomy_group=<some_group>, name=<some_name>,...)
profile = user.get_profile()
profile.taxonomies.add(taxonomy)

to retrieve you can do

profile.taxonomies.all()
domino
  • 2,137
  • 1
  • 22
  • 30