T
T
th3mis2016-12-27 17:23:44
Django
th3mis, 2016-12-27 17:23:44

How to automatically replace name with id?

Good day!
Now there is a table like this:

class TestResults(Base):
    id = Column(Integer, primary_key=True)
    test_name = Column(String)
    result = Column(Integer)

And each testing session, there are 1000 identical names in the table, sometimes, of course, the composition changes, but I want to get rid of duplication of names, referring to another table with a foreign key.
I want to remake it into this, and using a foreign key to get rid of data redundancy.
class TestName(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String)


class TestResults(Base):
    id = Column(Integer, primary_key=True)
    result = Column(Integer)
    name_id = Column(Integer, ForeignKey('test_name.id'), nullable=False)
    name = relationship("test_name", foreign_keys=[name_id])

So the question is, if you remake it into a new look, then before writing the results, you will have to make two queries in the code, or even three?
1. Find if there is already a test name in the name table, if not, then create it.
2. Create an entry referring to the id from step number 1.
Can I somehow organize two actions at the same time? Otherwise, in the write cycle, a thousand times two requests will be very long.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2016-12-27
@dimonchik2013

see update_or_create and get_or_create

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question