berinhard / model_mommy

No longer maintained, please migrate to model_bakery
http://model-bakery.readthedocs.org/
Other
903 stars 141 forks source link

Populate ForeignKey's attributes like django queryset field lookup #45

Closed berinhard closed 11 years ago

berinhard commented 12 years ago

Supose that we have two models:

from django.db import models

class Bar(models.Model):
    name = models.CharField(max_length=30)

class Foo(models.Model):
    bar = models.ForeignKey(Bar)

Now, imagine if we have a single test method that needs an instance of Foo which has a reference to a Bar's instance with a specif name value such as "Bob". In the current state of mode_mommy, the way to achieve this problem is just like the code bellow:

bar = mommy.make_one(Bar, name='Bob')
foo = mommy.make_one(Foo, bar=bar)

I'm imagining an API similar to Django Queryset Field Lookup. Something lke the following code:

foo = mommy.make_one(Foo, bar__name="Bob")

What do you think? I' want to work on this feature by now...

vandersonmota commented 12 years ago

Looks good. It would be good to work with prepare_one, since ForeignKeys associations are persisted. Also, it can work with recipes, in order to keep a consistent API.

berinhard commented 12 years ago

I've looked at the recipe API but I couldn't add this feature to that API.

This is because the recipe lays on creating a model instance given specific fields. At the ends, the recipes are quita a shortcut or alias to a Model.objects.create call. So, as it lays on fields explicitly determined I think this feature just doesn't make sense with the recipes API.

PS. I've updated the pull request updating the docs

vandersonmota commented 12 years ago

I'm thinking if we could use the Mommy's _make_one method in order to provide such thing.