Pregunta

In my web app,I have a m2m relation between a Category and a User

class Category(models.Model):
    users = models.ManyToManyField(User,related_name='category_users')
    title = models.CharField(max_length=200)
    description = models.TextField()

When a user tries to create a Category,I do this

category,created = Category.objects.get_or_create(title__iexact=category_title,defaults={'title':category_title,'description':category_title})

I need to provide the user with an edit page for Category.I thought to provide it such that only the person who created the category may edit the description. So,I tried to add a creator field in the model.

class Category(models.Model):
        users = models.ManyToManyField(User,related_name='category_users')
        title = models.CharField(max_length=200)
        description = models.TextField()
        creator = models.ForeignKey(User,related_name='category_creator')

However,this causes an IntegrityError when get_or_create() method is run,because creator_id is null

...
category_title = category_title_form.cleaned_data['title']
category_title = category_title.strip()
if len(category_title)>0:
            category,created = Category.objects.get_or_create(title__iexact=category_title,defaults={'title':category_title,'description':category_title})
            if request.user not in category.users.all():
                category.users.add(request.user)                
                category.save()
            if created:
                category.creator = request.user
            category.save()

Can someone tell me if there is a way I can solve this?

¿Fue útil?

Solución

When a user creates a category, you can add that category to the users "Category Set" --

category, created = user.category_set.get_or_create(
    title__iexact=category_title,
    defaults={'title': category_title, 'description': category_title}
)

By accessing the category table through user.category_set, the user_id field will be automatically maintained.

Only the user's categories can be retrieved through this call, and if it creates a new category, then the user_id will be set automatically.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top