user3541631
user3541631

Reputation: 4008

Using ManyToManyRelationship using 'trough'

I have 2 Entities/Models Person and Event.

There is a many to many connection between Person and Event, a Person can participate to multiple events, on an Event multiple Persons are going.

A person is not necessary to participate to an Event, an event can be empty.

I can do this in Django:

class Person(models.Model):

name = models.CharField(max_length=100)
event = models.ManyToManyField(Publication)  

This creates a related table with:

id | person_id | event_id

But I need a person to have more attributes related to Event, besides the keys, like Person's event number, Person's booth etc.

In Django documentation I found 'trough' model.

What is not clear(didn't found) is related to create/update/delete using forms so I need some examples and how querysets work;

Example:

  1. In a form I want to select and Event from a list and associated with the Person, and complete in the form the Person's event number, Person's booth etc.

  2. How can I use 1) as a formset, for the user on the same form/page to link multiple events to a Person.

  3. If an Event or a Person is deleted, is the 'trough' model record deleted automatically or need to do something manually ?

Upvotes: 0

Views: 27

Answers (1)

AKX
AKX

Reputation: 168967

Something like this oughta work.

class Person(models.Model):
    name = models.CharField(max_length=100)
    events = models.ManyToManyField('Event', through='Attendance')


class Event(models.Model):
    attendees = models.ManyToManyField('Person', through='Attendance')


class Attendance(models.Model):
    person = models.ForeignKey(Person, related_name='attendances', on_delete=models.CASCADE)
    event = models.ForeignKey(Event, related_name='attendances', on_delete=models.CASCADE)
    booth = models.CharField(max_length=10)

You can then simply create forms/formsets for Attendance objects. You can access an user's events through p.events.all(), or their attendances (with those extra infos) through p.attendances.all(). Similarly you can look at all the people attending an event through e.attendees.all(), etc.

Since on_delete=models.CASCADE is set, the Attendances will disappear when the event or person is deleted.

Upvotes: 1

Related Questions