Question

class Subscribers(User):
    date = models.DateField()
    user = models.OneToOneField(User)

class Tour(models.Model):
    """ This is not the id is a User object
    """
    owner_id = models.ForeignKey(User)
    name = models.CharField(max_length=50, primary_key=True)
    location = models.ManyToManyField(Location)
    subscribers = models.ManyToManyField(Subscribers, related_name="sub")

I am trying to test a method using:

def test_get_subsribers(self):
    user1= User.objects.create_user('Maria','j@j.com','j1')
    user4= User.objects.create_user('Giannis','m@m.com','m1')
    sub= Subscribers()
    sub.user = user4
    tour = Tour()
    tour.owner_id = user1
    tour.name = "Open Day"
    tour.subscribers.add(sub)
    self.assertEqual(get_subscribers("Open Day").count(),0)

But what I get is an error:

IntegrityError: insert or update on table "tour_tour_subscribers" violates foreign key constraint "tour_tour_subscribers_subscribers_id_fkey"
DETAIL:  Key (subscribers_id)=(10) is not present in table "tour_subscribers".

I am new in Django and I don't know how to fix this.

Was it helpful?

Solution

You try to add non-saved Subscriber to Tour.

You need to call sub.save() before tour.subscribers.add(sub)

The tour must also be saved before adding sub.

The reason for this is the additional table that handles many to many relations (see docs). This table stores two Foreign keys - one for Tour and one for Subscribers. To save a row into this table both Tour and Subscriber should exist in database

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top