WASD
WASD

Reputation: 320

How would I go about inserting data into one-to-many(must) relation, psycopg2/python in PostgreSQL

Using psycopg2/python how would I go about inserting data if I'd have something like from this img.

GRUPA (class GROUP) must contain one or more STUDENT's

How to fill them up and how to add them after, I can't add a GROUP without a student and I can't add a STUDENT w/o a GROUP.

Must it be a transaction/deferrable-constraints to add them in batch/together just to create GROUP?

What options do I have, how would you do it?

Thanks.

enter image description here

Upvotes: 0

Views: 238

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270401

I'm not sure why you have an id_group in the students table. It doesn't really make sense.

But if you do, make it null-able. Then you can:

  • Add a student into the table with a null value for id_group.
  • Add a group, with the student.
  • Update the students table with the value for the group.

However, you might also want to relax your requirements. For instance, perhaps a group could have no students. It wouldn't be a very active group, but the group can exist as a separate entity.

In fact, a more natural way to represent this data would be:

  • A students table with one row per student and no group reference.
  • A groups table with one row per group and no student reference.
  • A studentGroups table with one row per student in each group.

Upvotes: 1

Related Questions