berinhard/model_mommy

Can't set foreign keys data by id to model have unique field

Closed this issue · 5 comments

class FinancialYear(models.Model):
    ...
    year = models.IntegerField(unique=True, db_index=True)
    ...

class Bill(models.Model):
    financial_year = models.ForeignKey(FinancialYear)
    ...

when I call mommy.make(Bill, financial_year_id=1), it will auto create FinancialYear instance, though FinancialYear with id=1 is already exists.

I'm no expert here, but shouldn't mommy.make(Bill) create a FinancialYear object for you and include the ID of that object in the Bill object's financial_year value?

why not just pass the FinancialYear instance instead?

We encountered the same bug. It can worked around by doing:
mommy.make(Bill, financial_year=FinancialYear.objects.get(pk=1))

Even with the work around the model mommy should be smarter and not try and create an object for a foreign key when the id is provided.

@Jaredn
Because I need only one FinancialYear instance per year and some Bill instance refer to it. If model mommy auto create FinancialYear, test case will raise a duplicate key value error with FinancialYear's year field because model mommy don't check unique constraint for year field (it make dupplicate data for year field).
Sorry, I don't know English very well.

@vandersonmota
I can input id of object that have only one unique filed (id) and model mommy will work like a charm, but with object like FinancialYear (more unique field) it will create new FinancialYear object and end with raise a duplicate key value error.
Sorry, I don't know English very well.