-
Notifications
You must be signed in to change notification settings - Fork 51
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
Introducing IommiModel #325
Open
jlubcke
wants to merge
5
commits into
master
Choose a base branch
from
iommi_model
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
from django.core.exceptions import FieldDoesNotExist | ||
from django.db.models import Model | ||
|
||
|
||
class IommiModel(Model): | ||
class Meta: | ||
abstract = True | ||
|
||
iommi_ignored_attributes = () | ||
|
||
def __setattr__(self, name, value): | ||
if not name.startswith('_') and name != 'pk': | ||
try: | ||
field = self._meta.get_field(name) | ||
|
||
if getattr(field, 'primary_key', False): | ||
return object.__setattr__(self, name, value) | ||
|
||
except FieldDoesNotExist as e: | ||
if name not in self.iommi_ignored_attributes: | ||
raise TypeError( | ||
f'There is no field {name} on the model {self.__class__.__name__}. ' | ||
f'You can assign arbitrary attributes if they start with `_`. ' | ||
f'If this is an annotation, please add a tuple on the class named `iommi_ignored_attributes`' | ||
f'of valid annotated attributes that should not trigger this message.' | ||
) from e | ||
|
||
self.get_updated_fields().add(name) | ||
|
||
return object.__setattr__(self, name, value) | ||
|
||
def get_updated_fields(self): | ||
return self.__dict__.setdefault('_updated_fields', set()) | ||
|
||
@classmethod | ||
def from_db(cls, db, field_names, values): | ||
result = super().from_db(db, field_names, values) | ||
result.get_updated_fields().clear() | ||
return result | ||
|
||
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): | ||
if self.pk is not None and not force_insert: | ||
update_fields = self.get_updated_fields() | ||
|
||
super().save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields) | ||
|
||
self.get_updated_fields().clear() | ||
|
||
def __repr__(self): | ||
return f'<{self.__class__.__name__} pk={self.pk}>' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
import pytest | ||
from django.db.models import ( | ||
AutoField, | ||
CASCADE, | ||
Max, | ||
OneToOneField, | ||
) | ||
|
||
from iommi.model import IommiModel | ||
from tests.models import ( | ||
MyAnnotatedIommiModel, | ||
MyIommiModel, | ||
NoRaceConditionModel, | ||
RaceConditionModel, | ||
) | ||
|
||
|
||
def test_model(): | ||
m = MyIommiModel(foo=17) | ||
assert m.foo == 17 | ||
|
||
assert m.get_updated_fields() == {'foo'} | ||
|
||
|
||
def test_constructor_exception(): | ||
with pytest.raises(TypeError): | ||
MyIommiModel(bar=17) | ||
|
||
|
||
def test_attribute_exception(): | ||
m = MyIommiModel() | ||
m._bar = 17 | ||
with pytest.raises(TypeError): | ||
m.bar = 17 | ||
|
||
|
||
def test_reversed(): | ||
class MyOtherModel(IommiModel): | ||
bar = OneToOneField(MyIommiModel, related_name='other', on_delete=CASCADE) | ||
|
||
o = MyOtherModel(bar=MyIommiModel()) | ||
o.bar = MyIommiModel() | ||
|
||
MyIommiModel().other = MyOtherModel() | ||
|
||
|
||
def test_updated_fields(): | ||
m = MyIommiModel() | ||
m.foo = 17 | ||
|
||
assert m.get_updated_fields() == {'foo'} | ||
|
||
|
||
def test_ignore_pk_field(): | ||
class WeirdPKNameModel(IommiModel): | ||
this_is_a_pk = AutoField(primary_key=True) | ||
|
||
m = WeirdPKNameModel() | ||
|
||
assert m.get_updated_fields() == set() | ||
|
||
|
||
@pytest.mark.django_db | ||
def test_race_condition_on_save(): | ||
m = RaceConditionModel.objects.create(a=1, b=2) | ||
m2 = RaceConditionModel.objects.get(pk=m.pk) | ||
m2.b = 7 | ||
m2.save() | ||
|
||
m.a = 17 | ||
m.save() # This save() overwrites the value of b | ||
assert RaceConditionModel.objects.get(pk=m.pk).b == 2 | ||
|
||
|
||
@pytest.mark.django_db | ||
def test_no_race_condition_on_save(): | ||
m = NoRaceConditionModel.objects.create(a=1, b=2) | ||
m2 = NoRaceConditionModel.objects.get(pk=m.pk) | ||
assert m2.get_updated_fields() == set() | ||
m2.b = 7 | ||
assert m2.get_updated_fields() == {'b'} | ||
m2.save() | ||
|
||
m.a = 17 | ||
assert m.get_updated_fields() == {'a'} | ||
m.save() # This save() does NOT overwrite b! | ||
assert NoRaceConditionModel.objects.get(pk=m.pk).b == 7 | ||
assert not m.get_updated_fields() | ||
|
||
|
||
@pytest.mark.django_db | ||
def test_annotation(): | ||
MyIommiModel.objects.create(foo=2) | ||
with pytest.raises(TypeError): | ||
MyIommiModel.objects.annotate(fisk=Max('foo')).get() | ||
|
||
MyAnnotatedIommiModel.objects.create(foo=2) | ||
MyAnnotatedIommiModel.objects.annotate(fisk=Max('foo')).get() | ||
|
||
|
||
@pytest.mark.django_db | ||
def test_force_insert(): | ||
MyIommiModel.objects.create(pk=3, foo=1) | ||
|
||
|
||
def test_repr(): | ||
assert repr(MyIommiModel(pk=None, foo=1)) == '<MyIommiModel pk=None>' | ||
assert repr(MyIommiModel(pk=7, foo=1)) == '<MyIommiModel pk=7>' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we only do this if the user has not passed any other
update_fields
. (Or should we assert there are none? Or verify that the passed is a subset of what we expect?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Subset feels more logical. But it's also a bit weird... Maybe warn if update_fields is passed at all? My gut feeling is that you should pick a method, but also that you want it to be possible to slowly migrate to this system.