from django.db import models
from django.contrib.auth.models import User
class WorkDailyRecord(models.Model):
user = models.ForeignKey(User)
date = models.DateTimeField(auto_now=True)
contents = models.TextField()
check_user = models.ManyToManyField(User)
target_user = models.ManyToManyField(User)
ONGOING_OR_END =(
('ing', '진행중'),
('end', '완료'),
)
ongoing_or_end = models.CharField(
max_length=3,
choices=ONGOING_OR_END,
default='ing',
)
I write that code, then I’m give error…
So I search the Internet, and I find out that I must use ‘related_name’ attribute.
But I don’t know why I must use that attr??
Why??
By setting up an M2M to the
Usermodel,Userinstances will have an automaticworkdailyrecord_setattribute set on them. Since you need 2 accessors, django complains since it can’t setworkdailyrecord_settwice.If they allowed it, it would be very confusing indeed, as who knows what
user.workdailyrecord_setwould return in that case.You need to give it a
related_nameto differentiate between the two relationships pointing toUser.This way,
Userinstances will have aworkdailyrecord_targetreverse manager which will only queryWorkDailyRecordobjects related toUserby thetarget_userrelationship.e.g.
Unfortunately, you cannot disable this feature even using django’s documented
related_name='+'feature when it comes to M2Ms. Don’t ask me why 🙂