1

I've written a small tool that creates SQLAlchemy code from a written specification. The tool can create code like this:

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    address_id = db.Column(db.Integer, db.ForeignKey('address.id'))

class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50))

I can insert new records, I can query them, that works like a charm, but I would really like to not having to manually look for the Address of a Person.

I want to be able to access the address belonging to a specific person through the Person object. If I understand the examples correctly I need to do it like this (example based on http://flask-sqlalchemy.pocoo.org/2.1/models/#one-to-many-relationships)?

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    address = db.relationship('Address', backref='person',
                                lazy='dynamic')

class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50))
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'))

This looks to me all backwards, I have to give every Address a "link" to a Person and then backref so I can have an addresses for a person? Is this not possible to do directly from Person?

Also, creating code for this is much more complicated, so I'd really like to avoid that.

1 Answer 1

2

In the first example the Person can have exactly 1 address, but each address can be used by multiple Persons. In your second solution Person can now have multiple addresses, but each address is unique to a given Person (note that the ForeignKey moved tables).

So you went from N:1 to 1:N. By saying you want a list of the N-side, rather than the instance on the 1-side, you now have to specify more.

Sign up to request clarification or add additional context in comments.

1 Comment

I know, that's why I ask. There are no 1:1 examples I can find and the 1:N examples all have that (to me) superfluous backref thing going on. I would like to know how to do 1:1 the easiest way possible so I don't have to do a second query for the Address when I have the Person.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.