question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add SQLAlchemy support for get_or_create()

See original GitHub issue

I’m not sure this should be opened as an issue, but I can’t figure out how to do it…

Is there any way to re-use existing records with factory_boy, if they already exist? I can’t find anything in the documentation.

Here’s my scenario:

I’ve got an AddressFactory for my Address model. Every Address has an associated Country. I’d like to have my AddressFactory create the Country if it doesn’t exist, and re-use it if it does.

I know that I can create a Country manually, and pass it to the AddressFactory to be used. This works ok for a first-level nesting, but it gets complicated when there’s e.g. a User who has an Address which has a Country. I’d like to avoid having to pass it all the way down the chain.

For most fields, I get around this problem by using sequences to ensure unique names, etc. In this case, I’d really like to re-use existing countries.

I’ve tried to come up with a way to do this dynamically using lazy attributes, but haven’t had any luck so far.

Thanks!

Issue Analytics

  • State:closed
  • Created 10 years ago
  • Reactions:3
  • Comments:11 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
rbarroiscommented, Oct 3, 2020

This has finally been added last year 😉

0reactions
darkantheycommented, May 9, 2019

Another one SqlAlchemy avoid duplication implementation.

class StaticFactory(BaseFactory):
    __static_exclude = ('__static_exclude', '__static_cache',)
    __static_cache = {}
 
    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        """Helper for avoid duplicate factory"""
 
        # Exclude static cache
        cls._meta.exclude += cls.__static_exclude
 
        _unique_key = None
 
        # Get first unique keys from table. It'll be cache key.
        for col in model_class.__table__.columns:
            if any([col.primary_key, col.unique]):
                _unique_key = kwargs.get(col.name)
                if _unique_key:
                    break
 
        _instance = cls.__static_cache.get(_unique_key)
        if _instance:
            return _instance
 
        _session = cls._meta.sqlalchemy_session
        with _session.no_autoflush:
            obj = model_class(*args, **kwargs)
            _session.add(obj)
            cls.__static_cache.update({_unique_key: obj})
            return obj
 
class LanguageFactory(StaticFactory):
   xxx
Read more comments on GitHub >

github_iconTop Results From Across the Web

python - Does SQLAlchemy have an equivalent of Django's ...
EDIT: I've changed session.commit() to session.flush() as explained in ... from sqlalchemy import Column, String def get_or_create(self, ...
Read more >
sqlalchemy-get-or-create - PyPI
SQLAlchemy get_or_create(). SQLAlchemy versions of Django's get_or_create() and update_or_create(). Installation. To get the latest stable ...
Read more >
What is the equivalent of Django s get or create om ... - Edureka
Hi all. My requirement was that I needed to get my hands on an object from a ... session.add(instrument) return instrument All help...
Read more >
Object Relational Tutorial (1.x API)
This tutorial covers the well known SQLAlchemy ORM API that has been in use for many ... To persist our User object, we...
Read more >
Usage Guide — dogpile.cache 1.1.8 documentation
This “get-or-create” pattern is the entire key to the “Dogpile” system, ... from dogpile.cache import make_region region = make_region().configure( ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found