Buttons840
Buttons840

Reputation: 9657

Why can't I set the primary key in a django-dynamic-fixture fixture?

I have the following code:

class SampleModel(models.Model):
    sample_model_id = models.AutoField(primary_key=True)
    some_date = models.TextField()

def some_function():
    s = G(SampleModel, sample_model_id=1234, some_data='abcd')
    assert s.sample_model_id == 1
    assert s.some_data == 'abcd'

The assert statements pass (they are true statements). Any idea why I can't set the sample_model_id?

I am using Python 2.7, Django 1.4.5, and django-dynamic-fixture 1.6.5 (the latest version).

Upvotes: 0

Views: 596

Answers (1)

falsetru
falsetru

Reputation: 369494

class SampleModel(models.Model):
    some_data = models.TextField()

If I use above class (using automatic id field), I get expected result.

>>> from django_dynamic_fixture import G, get
>>> s = G(SampleModel, id=1234, some_data='abcd')
>>> s.id
1234
>>> s.some_data
'abcd'

With Sample model given in the question, get same result with the question.

Specifying id instead of sample_model_id raises an exception.

>>> s = G(SampleModel, id=1234, some_data='abcd')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/falsetru/.virtualenvs/django15/local/lib/python2.7/site-packages/django_dynamic_fixture/__init__.py", line 107, in get
    return d.get(model, shelve=shelve, **kwargs)
  File "/home/falsetru/.virtualenvs/django15/local/lib/python2.7/site-packages/django_dynamic_fixture/ddf.py", line 507, in get
    instance = self.new(model_class, shelve=shelve, named_shelve=named_shelve, **kwargs)
  File "/home/falsetru/.virtualenvs/django15/local/lib/python2.7/site-packages/django_dynamic_fixture/ddf.py", line 436, in new
    self.set_data_for_a_field(model_class, instance, field, persist_dependencies=persist_dependencies, **configuration)
  File "/home/falsetru/.virtualenvs/django15/local/lib/python2.7/site-packages/django_dynamic_fixture/ddf.py", line 348, in set_data_for_a_field
    data = self._process_field_with_default_fixture(field, model_class, persist_dependencies)
  File "/home/falsetru/.virtualenvs/django15/local/lib/python2.7/site-packages/django_dynamic_fixture/ddf.py", line 335, in _process_field_with_default_fixture
    data = self.data_fixture.generate_data(field)
  File "/usr/lib/python2.7/code.py", line 216, in interact
    sys.ps2
UnsupportedFieldError: polls.models.SampleModel.sample_model_id

UPDATE

Work around

Specify both id and sample_model_id.

>>> s = G(SampleModel, id=1234, sample_model_id=1234, some_data='abcd')
>>> s.sample_model_id
1234
>>> s.some_data
'abcd'

Actually, id value is not used internally; You can specify any value for id.

>>> s = G(SampleModel, id=None, sample_model_id=5555, some_data='abcd')
>>> s.sample_model_id
5555
>>> s.some_data
'abcd'

Upvotes: 2

Related Questions