0

I'm trying to extend django-taggit Tag model to have an added_by (ForeignKey to User) field on it, so I can query all tags added by a particular user. So, I have created an app and in models.py there I have created another model, called MyTag and I have a OneToOneField to Tag on it:

from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from taggit.models import Tag


class MyTag(models.Model):
    tag = models.OneToOneField(Tag, on_delete=models.CASCADE)
    added_by = models.ForeignKey(User, on_delete=models.CASCADE)

@receiver(post_save, sender=Tag)
def create_tag(sender, instance, created, **kwargs):
    if created:
        MyTag.objects.create(tag=instance, added_by=???)

@receiver(post_save, sender=Tag)
def save_tag(sender, instance, **kwargs):
    instance.mytag.save()

The issue is, I can't access request.user from inside models.py.

How do I overcome the issue, i.e. how do I properly extend django-taggit's Tag model to have added_by field on it?

adder
  • 3,512
  • 1
  • 16
  • 28
  • your question may be related to [this](https://stackoverflow.com/a/25717430/11225821) – Linh Nguyen Nov 22 '19 at 03:48
  • 1
    Have you looked into extending the `Tag` model and then overriding the `save()` method to accept `request.user`? This depends on who or how `Tag` model is used though. – Brian Destura Nov 22 '19 at 05:39

1 Answers1

0

I would recommend using inheritance instead of OneToOneField.

from taggit.models import Tag

class MyTag(Tag):
    added_by = models.ForeignKey(User, on_delete=models.CASCADE)

Now the MyTag model inherits all the properties and methods of the Tag model. More info here: https://docs.djangoproject.com/en/2.2/topics/db/models/#model-inheritance

Now to create a new instance of MyTag you can do in your view:

MyTag.objects.create(added_by=request.user , [... other Tag properties])
pe.kne
  • 655
  • 3
  • 16