New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DjangoModelFactory's "_setup_next_sequence" assumes that pk is an integer #57

Closed
AndrewIngram opened this Issue Apr 22, 2013 · 4 comments

Comments

Projects
None yet
3 participants
@AndrewIngram

AndrewIngram commented Apr 22, 2013

Offending code is here:

    @classmethod
    def _setup_next_sequence(cls):
        """Compute the next available PK, based on the 'pk' database field."""

        model = cls._associated_class  # pylint: disable=E1101
        manager = cls._get_manager(model)

        try:
            return 1 + manager.values_list('pk', flat=True
                ).order_by('-pk')[0]
        except IndexError:
            return 1

This problem didn't exist in factory_boy 1.3. My field that was using a non-integer PK is using a sequence, which worked fine previously:

code = factory.Sequence(lambda n: str(n).zfill(3))

I haven't dug into the code enough to know much about the changes that caused this problem, but ultimately I'd like to be able to use the sequence for the field again.

@rbarrois

This comment has been minimized.

Show comment
Hide comment
@rbarrois

rbarrois Apr 22, 2013

Member

This part of the code hasn't meaningfully changed since 1.3.0, where it was:

@classmethod
def _setup_next_sequence(cls):
    """Compute the next available PK, based on the 'pk' database field."""
    try:
        return 1 + cls._associated_class._default_manager.values_list('pk', flat=True
            ).order_by('-pk')[0]
    except IndexError:
        return 1

The v2.0.0 changed the default type of n in factory.Sequence from str to int, which might lead to the problem you're seeing.

If your pk is non-numeric, the supported way of handling this case is to override the _setup_next_sequence method:

class FooFactory(factory.DjangoModelFactory):
    FACTORY_FOR = models.Foo

    @classmethod
    def _setup_next_sequence(cls):
        return 1
Member

rbarrois commented Apr 22, 2013

This part of the code hasn't meaningfully changed since 1.3.0, where it was:

@classmethod
def _setup_next_sequence(cls):
    """Compute the next available PK, based on the 'pk' database field."""
    try:
        return 1 + cls._associated_class._default_manager.values_list('pk', flat=True
            ).order_by('-pk')[0]
    except IndexError:
        return 1

The v2.0.0 changed the default type of n in factory.Sequence from str to int, which might lead to the problem you're seeing.

If your pk is non-numeric, the supported way of handling this case is to override the _setup_next_sequence method:

class FooFactory(factory.DjangoModelFactory):
    FACTORY_FOR = models.Foo

    @classmethod
    def _setup_next_sequence(cls):
        return 1
@agriffis

This comment has been minimized.

Show comment
Hide comment
@agriffis

agriffis May 21, 2013

I ran into this problem too. Many of my Django models have non-integer PKs. Eventually I just monkey-patched it to catch the additional exception TypeError:

# Patch DjangoModelFactory to avoid TypeError if PK isn't an IntegerField
@classmethod
def _setup_next_sequence(cls):
    """Compute the next available PK, based on the 'pk' database field."""

    model = cls._associated_class  # pylint: disable=E1101
    manager = cls._get_manager(model)

    try:
        return 1 + manager.values_list('pk', flat=True
            ).order_by('-pk')[0]
    except (IndexError, TypeError):
        return 1

factory.DjangoModelFactory._setup_next_sequence = _setup_next_sequence

del _setup_next_sequence

However now that I think more about it, the code could be a bit safer by separating the exception handling. Something like this (untested):

@classmethod
def _setup_next_sequence(cls):
    """Compute the next available PK, based on the 'pk' database field."""

    model = cls._associated_class  # pylint: disable=E1101
    manager = cls._get_manager(model)

    try:
        last_key = manager.values_list('pk', flat=True
            ).order_by('-pk')[0]
    except IndexError:
        return 1

    if isinstance(last_key, int):
        return last_key + 1
    return 1

agriffis commented May 21, 2013

I ran into this problem too. Many of my Django models have non-integer PKs. Eventually I just monkey-patched it to catch the additional exception TypeError:

# Patch DjangoModelFactory to avoid TypeError if PK isn't an IntegerField
@classmethod
def _setup_next_sequence(cls):
    """Compute the next available PK, based on the 'pk' database field."""

    model = cls._associated_class  # pylint: disable=E1101
    manager = cls._get_manager(model)

    try:
        return 1 + manager.values_list('pk', flat=True
            ).order_by('-pk')[0]
    except (IndexError, TypeError):
        return 1

factory.DjangoModelFactory._setup_next_sequence = _setup_next_sequence

del _setup_next_sequence

However now that I think more about it, the code could be a bit safer by separating the exception handling. Something like this (untested):

@classmethod
def _setup_next_sequence(cls):
    """Compute the next available PK, based on the 'pk' database field."""

    model = cls._associated_class  # pylint: disable=E1101
    manager = cls._get_manager(model)

    try:
        last_key = manager.values_list('pk', flat=True
            ).order_by('-pk')[0]
    except IndexError:
        return 1

    if isinstance(last_key, int):
        return last_key + 1
    return 1
@rbarrois

This comment has been minimized.

Show comment
Hide comment
@rbarrois

rbarrois May 22, 2013

Member

@agriffis That's indeed a great idea, and should work much better for all uses.
Could you make that into a pull request?

Member

rbarrois commented May 22, 2013

@agriffis That's indeed a great idea, and should work much better for all uses.
Could you make that into a pull request?

@rbarrois

This comment has been minimized.

Show comment
Hide comment
@rbarrois

rbarrois Jun 9, 2013

Member

Fixed in 83461f0.

Member

rbarrois commented Jun 9, 2013

Fixed in 83461f0.

@rbarrois rbarrois closed this Jun 9, 2013

rbarrois added a commit that referenced this issue Jun 9, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment