0

I need to define a Meeting model which includes an organiser and a number of participants. All participants are derived from the standard User in auth module.

from django.db import models
from django.contrib.auth.models import User

class Meeting(models.Model):
    organizer=models.ForeignKey(User)
    participants=models.ManyToManyField(User)

However, when running syncdb, the I got the following error

Error: One or more models did not validate: hub.meeting: Accessor for field 'organizer' clashes with related m2m field 'User.meeting_set'. Add a related_name argument to the definition for 'organizer'. hub.meeting: Accessor for m2m field 'participants' clashes with related field 'User.meeting_set'. Add a related_name argument to the definition for 'participants'.

Can anyone help me to solve this?

thoaionline
  • 518
  • 2
  • 5
  • 14

2 Answers2

3
class Meeting(models.Model):
    organizer=models.ForeignKey(User, related_name="meetings_orginizer")
    participants=models.ManyToManyField(User, related_name="meetings_participants")

If you have a user object and you want to follow the relationship backwards to find either the meetings that user is an organizer of or meetings that the user is a participant of, you need to specifically name a 'related_name' field on the model to distinguish them. Now you can follow the relationship backwards like so:

me = User.objects.get(id=0)
# Meetings I'm organising
m1 = me.meetings_orginizer.all()
# Meetings I'm participating in
m2 = me.meetings_participants.all()
Community
  • 1
  • 1
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
1

the problem (as stated by the error message) has to do with backwards relations. when you define a foreign key (or many2many), django sets up a reverse relation User.meeting_set. however, since you have two relations, the reverse relations clash and you have to specify the related names manually. see the docs here and here

code as in answer above

second
  • 28,029
  • 7
  • 75
  • 76