def test_child_updates_without_ids(self): john = BandMember(name='John Lennon') beatles = Band(name='The Beatles', members=[ john ]) beatles.save() john_id = john.id paul = BandMember(name='Paul McCartney') beatles.members.add(paul) BandMembersFormset = childformset_factory(Band, BandMember, extra=3) band_members_formset = BandMembersFormset({ 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 2, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'John Lennon', 'form-0-id': john_id, 'form-1-name': 'Paul McCartney', # NB no way to know programmatically that this form corresponds to the 'paul' object 'form-1-id': '', }, instance=beatles) self.assertTrue(band_members_formset.is_valid()) band_members_formset.save(commit=False) self.assertEqual(2, beatles.members.count())
def test_child_updates_without_ids(self): first_song = Song(name='I Saw Her Standing There') album = Album(name='Please Please Me', songs=[first_song]) beatles = Band(name='The Beatles', albums=[album]) beatles.save() first_song_id = first_song.id second_song = Song(name='Misery') album.songs.add(second_song) AlbumsFormset = childformset_factory(Band, Album, form=ClusterForm, extra=3) albums_formset = AlbumsFormset({ 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'Please Please Me', 'form-0-id': album.id, 'form-0-songs-TOTAL_FORMS': 2, 'form-0-songs-INITIAL_FORMS': 2, 'form-0-songs-MAX_NUM_FORMS': 1000, 'form-0-songs-0-name': 'I Saw Her Standing There', 'form-0-songs-0-id': first_song_id, 'form-0-songs-1-name': 'Misery', 'form-0-songs-1-id': '', }, instance=beatles) self.assertTrue(albums_formset.is_valid()) albums_formset.save(commit=False) self.assertEqual(2, beatles.albums.first().songs.count())
def test_queryset_filtering(self): beatles = Band(name='The Beatles', members=[ BandMember(id=1, name='John Lennon'), BandMember(id=2, name='Paul McCartney'), ]) self.assertEqual('Paul McCartney', beatles.members.get(id=2).name) self.assertEqual('Paul McCartney', beatles.members.get(id='2').name) self.assertEqual(1, beatles.members.filter(name='Paul McCartney').count()) # also need to be able to filter on foreign fields that return a model instance # rather than a simple python value self.assertEqual(2, beatles.members.filter(band=beatles).count()) # and ensure that the comparison is not treating all unsaved instances as identical rutles = Band(name='The Rutles') self.assertEqual(0, beatles.members.filter(band=rutles).count()) # and the comparison must be on the model instance's ID where available, # not by reference beatles.save() beatles.members.add( BandMember(id=3, name='George Harrison') ) # modify the relation so that we're not to a plain database-backed queryset also_beatles = Band.objects.get(id=beatles.id) self.assertEqual(3, beatles.members.filter(band=also_beatles).count())
def test_copy_child_relations_between_saved_objects(self): # This test copies child relations between two saved objects # This also shouldn't commit the new child objects to the database self.beatles.save() john = self.beatles.members.get(name='John Lennon') paul = self.beatles.members.get(name='Paul McCartney') beatles_clone = Band(name='The Beatles 2020 comeback') beatles_clone.save() child_object_mapping = self.beatles.copy_child_relation( 'members', beatles_clone) new_john = beatles_clone.members.get(name='John Lennon') new_paul = beatles_clone.members.get(name='Paul McCartney') self.assertIsNone(new_john.pk) self.assertIsNone(new_paul.pk) self.assertEqual(new_john.band, beatles_clone) self.assertEqual(new_paul.band, beatles_clone) self.assertEqual( child_object_mapping, { (band_members_rel, john.pk): new_john, (band_members_rel, paul.pk): new_paul, })
def test_commit(self): # The commit parameter will instruct the method to save the child objects straight away self.beatles.save() john = self.beatles.members.get(name='John Lennon') paul = self.beatles.members.get(name='Paul McCartney') beatles_clone = Band(name='The Beatles 2020 comeback') beatles_clone.save() child_object_mapping = self.beatles.copy_child_relation('members', beatles_clone, commit=True) new_john = beatles_clone.members.get(name='John Lennon') new_paul = beatles_clone.members.get(name='Paul McCartney') self.assertIsNotNone(new_john.pk) self.assertIsNotNone(new_paul.pk) self.assertEqual(new_john.band, beatles_clone) self.assertEqual(new_paul.band, beatles_clone) self.assertEqual( child_object_mapping, { (band_members_rel, john.pk): new_john, (band_members_rel, paul.pk): new_paul, })
def test_append(self): # But you can specify append=True, which appends them to the existing list self.beatles.save() john = self.beatles.members.get(name='John Lennon') paul = self.beatles.members.get(name='Paul McCartney') beatles_clone = Band(name='The Beatles 2020 comeback') beatles_clone.members.add(BandMember(name='Julian Lennon')) beatles_clone.save() self.assertTrue( beatles_clone.members.filter(name='Julian Lennon').exists()) child_object_mapping = self.beatles.copy_child_relation('members', beatles_clone, append=True) self.assertTrue( beatles_clone.members.filter(name='Julian Lennon').exists()) new_john = beatles_clone.members.get(name='John Lennon') new_paul = beatles_clone.members.get(name='Paul McCartney') self.assertIsNone(new_john.pk) self.assertIsNone(new_paul.pk) self.assertEqual(new_john.band, beatles_clone) self.assertEqual(new_paul.band, beatles_clone) self.assertEqual( child_object_mapping, { (band_members_rel, john.pk): new_john, (band_members_rel, paul.pk): new_paul, })
def test_serialize(self): beatles = Band(name='The Beatles', members=[ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ]) expected = {'pk': None, 'albums': [], 'name': 'The Beatles', 'members': [{'pk': None, 'name': 'John Lennon', 'band': None}, {'pk': None, 'name': 'Paul McCartney', 'band': None}]} self.assertEqual(expected, beatles.serializable_data())
def test_incoming_form_data(self): class BandForm(ClusterForm): class Meta: model = Band fields = ['name'] beatles = Band(name='The Beatles', albums=[ Album(name='Please Please Me', songs=[ Song(name='I Saw Her Standing There') ]), ]) form = BandForm({ 'name': 'The Beatles', 'members-TOTAL_FORMS': 0, 'members-INITIAL_FORMS': 0, 'members-MAX_NUM_FORMS': 1000, 'albums-TOTAL_FORMS': 1, 'albums-INITIAL_FORMS': 0, 'albums-MAX_NUM_FORMS': 1000, 'albums-0-name': 'Please Please Me', 'albums-0-id': '', 'albums-0-ORDER': 1, 'albums-0-songs-TOTAL_FORMS': 2, 'albums-0-songs-INITIAL_FORMS': 1, 'albums-0-songs-MAX_NUM_FORMS': 1000, 'albums-0-songs-0-name': 'I Saw Her Standing There', 'albums-0-songs-0-DELETE': 'albums-0-songs-0-DELETE', 'albums-0-songs-0-id': '', 'albums-0-songs-1-name': 'Misery', 'albums-0-songs-1-id': '', }, instance=beatles) self.assertTrue(form.is_valid()) result = form.save(commit=False) self.assertEqual(result, beatles) self.assertEqual(1, beatles.albums.count()) self.assertEqual('Please Please Me', beatles.albums.first().name) self.assertEqual(1, beatles.albums.first().songs.all().count()) self.assertEqual('Misery', beatles.albums.first().songs.first().name) # should not exist in the database yet self.assertFalse(Album.objects.filter(name='Please Please Me').exists()) self.assertFalse(Song.objects.filter(name='Misery').exists()) beatles.save() # this should create database entries self.assertTrue(Band.objects.filter(name='The Beatles').exists()) self.assertTrue(Album.objects.filter(name='Please Please Me').exists()) self.assertTrue(Song.objects.filter(name='Misery').exists()) self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
def test_save_commit_false(self): first_song = Song(name='I Saw Her Standing There') second_song = Song(name='Mystery') album = Album(name='Please Please Me', songs=[first_song, second_song]) beatles = Band(name='The Beatles', albums=[album]) beatles.save() first_song_id, second_song_id = first_song.id, second_song.id AlbumsFormset = childformset_factory(Band, Album, form=ClusterForm, extra=3) albums_formset = AlbumsFormset({ 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'Please Please Me', 'form-0-id': album.id, 'form-0-songs-TOTAL_FORMS': 4, 'form-0-songs-INITIAL_FORMS': 2, 'form-0-songs-MAX_NUM_FORMS': 1000, 'form-0-songs-0-name': 'I Saw Her Standing There', 'form-0-songs-0-DELETE': 'form-0-songs-0-DELETE', 'form-0-songs-0-id': first_song_id, 'form-0-songs-1-name': 'Misery', # changing data of an existing record 'form-0-songs-1-id': second_song_id, 'form-0-songs-2-name': '', 'form-0-songs-2-id': '', 'form-0-songs-3-name': 'Chains', # adding a record 'form-0-songs-3-id': '', }, instance=beatles) self.assertTrue(albums_formset.is_valid()) updated_albums = albums_formset.save(commit=False) # updated_members should only include the items that have been changed and not deleted self.assertEqual(1, len(updated_albums)) self.assertEqual('Please Please Me', updated_albums[0].name) self.assertEqual(2, updated_albums[0].songs.count()) self.assertEqual('Misery', updated_albums[0].songs.first().name) self.assertEqual(second_song_id, updated_albums[0].songs.first().id) self.assertEqual('Chains', updated_albums[0].songs.all()[1].name) self.assertEqual(None, updated_albums[0].songs.all()[1].id) # Changes should not be committed to the db yet self.assertTrue(Song.objects.filter(name='I Saw Her Standing There', id=first_song_id).exists()) self.assertEqual('Mystery', Song.objects.get(id=second_song_id).name) self.assertFalse(Song.objects.filter(name='Chains').exists()) beatles.albums.first().songs.commit() # this should create/update/delete database entries self.assertEqual('Misery', Song.objects.get(id=second_song_id).name) self.assertTrue(Song.objects.filter(name='Chains').exists()) self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
def test_can_only_commit_on_saved_parent(self): beatles = Band(name='The Beatles', members=[ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ]) self.assertRaises(IntegrityError, lambda: beatles.members.commit()) beatles.save() beatles.members.commit()
def test_save_commit_false(self): john = BandMember(name='John Lennon') paul = BandMember(name='Paul McCartney') ringo = BandMember(name='Richard Starkey') beatles = Band(name='The Beatles', members=[john, paul, ringo]) beatles.save() john_id, paul_id, ringo_id = john.id, paul.id, ringo.id BandMembersFormset = childformset_factory(Band, BandMember, extra=3) band_members_formset = BandMembersFormset( { 'form-TOTAL_FORMS': 5, 'form-INITIAL_FORMS': 3, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'John Lennon', 'form-0-DELETE': 'form-0-DELETE', 'form-0-id': john_id, 'form-1-name': 'Paul McCartney', 'form-1-id': paul_id, 'form-2-name': 'Ringo Starr', # changing data of an existing record 'form-2-id': ringo_id, 'form-3-name': '', 'form-3-id': '', 'form-4-name': 'George Harrison', # adding a record 'form-4-id': '', }, instance=beatles) self.assertTrue(band_members_formset.is_valid()) updated_members = band_members_formset.save(commit=False) # updated_members should only include the items that have been changed and not deleted self.assertEqual(2, len(updated_members)) self.assertEqual('Ringo Starr', updated_members[0].name) self.assertEqual(ringo_id, updated_members[0].id) self.assertEqual('George Harrison', updated_members[1].name) self.assertEqual(None, updated_members[1].id) # Changes should not be committed to the db yet self.assertTrue( BandMember.objects.filter(name='John Lennon', id=john_id).exists()) self.assertEqual('Richard Starkey', BandMember.objects.get(id=ringo_id).name) self.assertFalse( BandMember.objects.filter(name='George Harrison').exists()) beatles.members.commit() # this should create/update/delete database entries self.assertEqual('Ringo Starr', BandMember.objects.get(id=ringo_id).name) self.assertTrue( BandMember.objects.filter(name='George Harrison').exists()) self.assertFalse( BandMember.objects.filter(name='John Lennon').exists())
def test_saved_items(self): class BandForm(ClusterForm): class Meta: model = Band fields = ['name'] first_song = Song(name='I Saw Her Standing There') second_song = Song(name='Misery') album = Album(name='Please Please Me', songs=[first_song, second_song]) beatles = Band(name='The Beatles', albums=[album]) beatles.save() self.assertTrue(album.id) self.assertTrue(first_song.id) self.assertTrue(second_song.id) form = BandForm({ 'name': 'The Beatles', 'members-TOTAL_FORMS': 0, 'members-INITIAL_FORMS': 0, 'members-MAX_NUM_FORMS': 1000, 'albums-TOTAL_FORMS': 1, 'albums-INITIAL_FORMS': 1, 'albums-MAX_NUM_FORMS': 1000, 'albums-0-name': album.name, 'albums-0-id': album.id, 'albums-0-ORDER': 1, 'albums-0-songs-TOTAL_FORMS': 4, 'albums-0-songs-INITIAL_FORMS': 2, 'albums-0-songs-MAX_NUM_FORMS': 1000, 'albums-0-songs-0-name': first_song.name, 'albums-0-songs-0-DELETE': 'albums-0-songs-0-DELETE', 'albums-0-songs-0-id': first_song.id, 'albums-0-songs-1-name': second_song.name, 'albums-0-songs-1-id': second_song.id, 'albums-0-songs-2-name': 'Anna', 'albums-0-songs-2-id': '', 'albums-0-songs-3-name': '', 'albums-0-songs-3-id': '', }, instance=beatles) self.assertTrue(form.is_valid()) form.save() self.assertTrue(Song.objects.filter(name='Anna').exists()) self.assertTrue(Song.objects.filter(name='Misery').exists()) self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
def test_save_commit_false(self): john = BandMember(name='John Lennon') paul = BandMember(name='Paul McCartney') ringo = BandMember(name='Richard Starkey') beatles = Band(name='The Beatles', members=[ john, paul, ringo ]) beatles.save() john_id, paul_id, ringo_id = john.id, paul.id, ringo.id BandMembersFormset = childformset_factory(Band, BandMember, extra=3) band_members_formset = BandMembersFormset({ 'form-TOTAL_FORMS': 5, 'form-INITIAL_FORMS': 3, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'John Lennon', 'form-0-DELETE': 'form-0-DELETE', 'form-0-id': john_id, 'form-1-name': 'Paul McCartney', 'form-1-id': paul_id, 'form-2-name': 'Ringo Starr', # changing data of an existing record 'form-2-id': ringo_id, 'form-3-name': '', 'form-3-id': '', 'form-4-name': 'George Harrison', # adding a record 'form-4-id': '', }, instance=beatles) self.assertTrue(band_members_formset.is_valid()) updated_members = band_members_formset.save(commit=False) # updated_members should only include the items that have been changed and not deleted self.assertEqual(2, len(updated_members)) self.assertEqual('Ringo Starr', updated_members[0].name) self.assertEqual(ringo_id, updated_members[0].id) self.assertEqual('George Harrison', updated_members[1].name) self.assertEqual(None, updated_members[1].id) # Changes should not be committed to the db yet self.assertTrue(BandMember.objects.filter(name='John Lennon', id=john_id).exists()) self.assertEqual('Richard Starkey', BandMember.objects.get(id=ringo_id).name) self.assertFalse(BandMember.objects.filter(name='George Harrison').exists()) beatles.members.commit() # this should create/update/delete database entries self.assertEqual('Ringo Starr', BandMember.objects.get(id=ringo_id).name) self.assertTrue(BandMember.objects.filter(name='George Harrison').exists()) self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())
def setUp(self): self.beatles = Band(name='The Beatles', members=[ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ], albums=[ Album(name='Please Please Me', sort_order=1), Album(name='With The Beatles', sort_order=2), Album(name='Abbey Road', sort_order=3), ])
def test_ignore_validation_on_deleted_items(self): class BandForm(ClusterForm): class Meta: model = Band fields = ['name'] please_please_me = Album(name='Please Please Me', release_date=datetime.date(1963, 3, 22)) beatles = Band(name='The Beatles', albums=[please_please_me]) beatles.save() form = BandForm({ 'name': "The Beatles", 'members-TOTAL_FORMS': 0, 'members-INITIAL_FORMS': 0, 'members-MAX_NUM_FORMS': 1000, 'albums-TOTAL_FORMS': 1, 'albums-INITIAL_FORMS': 1, 'albums-MAX_NUM_FORMS': 1000, 'albums-0-name': 'With The Beatles', 'albums-0-release_date': '1963-02-31', # invalid date 'albums-0-id': please_please_me.id, 'albums-0-ORDER': 1, }, instance=beatles) self.assertFalse(form.is_valid()) form = BandForm({ 'name': "The Beatles", 'members-TOTAL_FORMS': 0, 'members-INITIAL_FORMS': 0, 'members-MAX_NUM_FORMS': 1000, 'albums-TOTAL_FORMS': 1, 'albums-INITIAL_FORMS': 1, 'albums-MAX_NUM_FORMS': 1000, 'albums-0-name': 'With The Beatles', 'albums-0-release_date': '1963-02-31', # invalid date 'albums-0-id': please_please_me.id, 'albums-0-ORDER': 1, 'albums-0-DELETE': 'albums-0-DELETE', }, instance=beatles) self.assertTrue(form.is_valid()) form.save(commit=False) self.assertEqual(0, beatles.albums.count()) self.assertEqual(1, Band.objects.get(id=beatles.id).albums.count()) beatles.save() self.assertEqual(0, Band.objects.get(id=beatles.id).albums.count())
def test_saved_items_with_non_db_relation(self): class BandForm(ClusterForm): class Meta: model = Band fields = ['name'] first_song = Song(name='I Saw Her Standing There') second_song = Song(name='Misery') album = Album(name='Please Please Me', songs=[first_song, second_song]) beatles = Band(name='The Beatles', albums=[album]) beatles.save() # pack and unpack the record so that we're working with a non-db-backed queryset new_beatles = Band.from_json(beatles.to_json()) form = BandForm({ 'name': 'The Beatles', 'members-TOTAL_FORMS': 0, 'members-INITIAL_FORMS': 0, 'members-MAX_NUM_FORMS': 1000, 'albums-TOTAL_FORMS': 1, 'albums-INITIAL_FORMS': 1, 'albums-MAX_NUM_FORMS': 1000, 'albums-0-name': album.name, 'albums-0-id': album.id, 'albums-0-ORDER': 1, 'albums-0-songs-TOTAL_FORMS': 4, 'albums-0-songs-INITIAL_FORMS': 2, 'albums-0-songs-MAX_NUM_FORMS': 1000, 'albums-0-songs-0-name': first_song.name, 'albums-0-songs-0-DELETE': 'albums-0-songs-0-DELETE', 'albums-0-songs-0-id': first_song.id, 'albums-0-songs-1-name': second_song.name, 'albums-0-songs-1-id': second_song.id, 'albums-0-songs-2-name': 'Anna', 'albums-0-songs-2-id': '', 'albums-0-songs-3-name': '', 'albums-0-songs-3-id': '', }, instance=new_beatles) self.assertTrue(form.is_valid()) form.save() self.assertTrue(Song.objects.filter(name='Anna').exists()) self.assertFalse(Song.objects.filter(name='I Saw Her Standing There').exists())
def test_serialize_json_with_dates(self): beatles = Band(name='The Beatles', members=[ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ], albums=[ Album(name='Rubber Soul', release_date=datetime.date(1965, 12, 3)) ]) beatles_json = beatles.to_json() self.assertTrue("John Lennon" in beatles_json) self.assertTrue("1965-12-03" in beatles_json) unpacked_beatles = Band.from_json(beatles_json) self.assertEqual(datetime.date(1965, 12, 3), unpacked_beatles.albums.all()[0].release_date)
def test_incoming_form_data(self): class BandForm(ClusterForm): class Meta: model = Band fields = ['name'] beatles = Band(name='The Beatles', members=[ BandMember(name='George Harrison'), ]) form = BandForm({ 'name': "The Beatles", 'members-TOTAL_FORMS': 4, 'members-INITIAL_FORMS': 1, 'members-MAX_NUM_FORMS': 1000, 'members-0-name': 'George Harrison', 'members-0-DELETE': 'members-0-DELETE', 'members-0-id': '', 'members-1-name': 'John Lennon', 'members-1-id': '', 'members-2-name': 'Paul McCartney', 'members-2-id': '', 'members-3-name': '', 'members-3-id': '', 'albums-TOTAL_FORMS': 0, 'albums-INITIAL_FORMS': 0, 'albums-MAX_NUM_FORMS': 1000, }, instance=beatles) self.assertTrue(form.is_valid()) result = form.save(commit=False) self.assertEqual(result, beatles) self.assertEqual(2, beatles.members.count()) self.assertEqual('John Lennon', beatles.members.all()[0].name) # should not exist in the database yet self.assertFalse(BandMember.objects.filter(name='John Lennon').exists()) beatles.save() # this should create database entries self.assertTrue(Band.objects.filter(name='The Beatles').exists()) self.assertTrue(BandMember.objects.filter(name='John Lennon').exists())
def test_copy_child_relations_from_saved_to_unsaved_object(self): # This test clones the beatles from a previously saved band/child objects. # The only difference here is we can return the old IDs in the mapping. self.beatles.save() john = self.beatles.members.get(name='John Lennon') paul = self.beatles.members.get(name='Paul McCartney') beatles_clone = Band(name='The Beatles 2020 comeback') child_object_mapping = self.beatles.copy_child_relation( 'members', beatles_clone) new_john = beatles_clone.members.get(name='John Lennon') new_paul = beatles_clone.members.get(name='Paul McCartney') self.assertIsNone(new_john.pk) self.assertIsNone(new_paul.pk) self.assertEqual(new_john.band, beatles_clone) self.assertEqual(new_paul.band, beatles_clone) # The objects are saved in the source, so we can give each item it's own entry in the mapping self.assertEqual( child_object_mapping, { (band_members_rel, john.pk): new_john, (band_members_rel, paul.pk): new_paul, })
def test_related_manager_assignment_ops(self): beatles = Band(name='The Beatles') john = BandMember(name='John Lennon') paul = BandMember(name='Paul McCartney') beatles.members.add(john) self.assertEqual(1, beatles.members.count()) beatles.members.add(paul) self.assertEqual(2, beatles.members.count()) # ensure that duplicates are filtered beatles.members.add(paul) self.assertEqual(2, beatles.members.count()) beatles.members.remove(john) self.assertEqual(1, beatles.members.count()) self.assertEqual(paul, beatles.members.all()[0]) george = beatles.members.create(name='George Harrison') self.assertEqual(2, beatles.members.count()) self.assertEqual('George Harrison', george.name) beatles.members.set([john]) self.assertEqual(1, beatles.members.count()) self.assertEqual(john, beatles.members.all()[0])
def test_incoming_formset_data(self): beatles = Band(name='The Beatles', members=[ BandMember(name='George Harrison'), ]) band_members_formset = self.BandMembersFormset({ 'form-TOTAL_FORMS': 3, 'form-INITIAL_FORMS': 1, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'John Lennon', 'form-0-id': '', 'form-1-name': 'Paul McCartney', 'form-1-id': '', 'form-2-name': '', 'form-2-id': '', }, queryset=beatles.members.all()) self.assertTrue(band_members_formset.is_valid()) members = band_members_formset.save(commit=False) self.assertEqual(2, len(members)) self.assertEqual('John Lennon', members[0].name) # should not exist in the database yet self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())
def test_copy_all_child_relations_saved(self): self.beatles.save() john = self.beatles.members.get(name='John Lennon') paul = self.beatles.members.get(name='Paul McCartney') album_1 = self.beatles.albums.get(sort_order=1) album_2 = self.beatles.albums.get(sort_order=2) album_3 = self.beatles.albums.get(sort_order=3) beatles_clone = Band(name='The Beatles 2020 comeback') child_object_mapping = self.beatles.copy_all_child_relations( beatles_clone) new_john = beatles_clone.members.get(name='John Lennon') new_paul = beatles_clone.members.get(name='Paul McCartney') new_album_1 = beatles_clone.albums.get(sort_order=1) new_album_2 = beatles_clone.albums.get(sort_order=2) new_album_3 = beatles_clone.albums.get(sort_order=3) self.assertEqual( child_object_mapping, { (band_members_rel, john.pk): new_john, (band_members_rel, paul.pk): new_paul, (band_albums_rel, album_1.pk): new_album_1, (band_albums_rel, album_2.pk): new_album_2, (band_albums_rel, album_3.pk): new_album_3, })
def test_deserialize_with_sort_order(self): beatles = Band.from_json('{"pk": null, "albums": [{"pk": null, "name": "With The Beatles", "sort_order": 2}, {"pk": null, "name": "Please Please Me", "sort_order": 1}], "name": "The Beatles", "members": []}') self.assertEqual(2, beatles.albums.count()) # Make sure the albums were ordered correctly self.assertEqual("Please Please Me", beatles.albums.all()[0].name) self.assertEqual("With The Beatles", beatles.albums.all()[1].name)
def test_deserialize(self): beatles = Band.from_serializable_data({ 'pk': 9, 'albums': [], 'name': 'The Beatles', 'members': [ {'pk': None, 'name': 'John Lennon', 'band': None}, {'pk': None, 'name': 'Paul McCartney', 'band': None}, ] }) self.assertEqual(9, beatles.id) self.assertEqual('The Beatles', beatles.name) self.assertEqual(2, beatles.members.count()) self.assertEqual(BandMember, beatles.members.all()[0].__class__) authors = {} categories = {} for ii in range(1, 6): authors[ii] = Author.objects.create(name="Author " + str(ii)) categories[ii] = Category.objects.create(name="Category " + str(ii)) article = Article.from_serializable_data({ 'pk': 1, 'title': 'Article Title 1', 'authors': [authors[1].pk, authors[2].pk], 'categories': [categories[2].pk, categories[3].pk, categories[4].pk] }) self.assertEqual(article.id, 1) self.assertEqual(article.title, 'Article Title 1') self.assertEqual(article.authors.count(), 2) self.assertEqual([author.name for author in article.authors.all()], ['Author 1', 'Author 2']) self.assertEqual(article.categories.count(), 3)
def test_can_pass_child_relations_as_constructor_kwargs(self): beatles = Band(name='The Beatles', members=[ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ]) self.assertEqual(2, beatles.members.count()) self.assertEqual(beatles, beatles.members.all()[0].band)
def test_append(self): beatles_clone = Band(name='The Beatles 2020 comeback') beatles_clone.members.add(BandMember(name='Julian Lennon')) self.assertTrue( beatles_clone.members.filter(name='Julian Lennon').exists()) child_object_mapping = self.beatles.copy_all_child_relations( beatles_clone, append=True) self.assertTrue( beatles_clone.members.filter(name='Julian Lennon').exists()) new_john = beatles_clone.members.get(name='John Lennon') new_paul = beatles_clone.members.get(name='Paul McCartney') new_album_1 = beatles_clone.albums.get(sort_order=1) new_album_2 = beatles_clone.albums.get(sort_order=2) new_album_3 = beatles_clone.albums.get(sort_order=3) self.assertIsNone(new_john.pk) self.assertIsNone(new_paul.pk) self.assertEqual(new_john.band, beatles_clone) self.assertEqual(new_paul.band, beatles_clone) self.assertEqual( child_object_mapping, { (band_members_rel, None): [new_john, new_paul], (band_albums_rel, None): [new_album_1, new_album_2, new_album_3], })
def test_saving_formset_preserves_order(self): AlbumsFormset = childformset_factory(Band, Album, extra=3, can_order=True) beatles = Band(name='The Beatles') albums_formset = AlbumsFormset( { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'With The Beatles', 'form-0-id': '', 'form-0-ORDER': '2', 'form-1-name': 'Please Please Me', 'form-1-id': '', 'form-1-ORDER': '1', }, instance=beatles) self.assertTrue(albums_formset.is_valid()) albums_formset.save(commit=False) album_names = [album.name for album in beatles.albums.all()] self.assertEqual(['Please Please Me', 'With The Beatles'], album_names)
def test_save_commit_false(self): john = BandMember(name='John Lennon') paul = BandMember(name='Paul McCartney') ringo = BandMember(name='Richard Starkey') beatles = Band(name='The Beatles', members=[ john, paul, ringo ]) beatles.save() john_id, paul_id, ringo_id = john.id, paul.id, ringo.id self.assertTrue(john_id) self.assertTrue(paul_id) band_members_formset = self.BandMembersFormset({ 'form-TOTAL_FORMS': 5, 'form-INITIAL_FORMS': 3, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'John Lennon', 'form-0-DELETE': 'form-0-DELETE', 'form-0-id': john_id, 'form-1-name': 'Paul McCartney', 'form-1-id': paul_id, 'form-2-name': 'Ringo Starr', # changing data of an existing record 'form-2-id': ringo_id, 'form-3-name': '', 'form-3-id': '', 'form-4-name': 'George Harrison', # Adding a record 'form-4-id': '', }, queryset=beatles.members.all()) self.assertTrue(band_members_formset.is_valid()) updated_members = band_members_formset.save(commit=False) self.assertEqual(2, len(updated_members)) self.assertEqual('Ringo Starr', updated_members[0].name) self.assertEqual(ringo_id, updated_members[0].id) # should not be updated in the db yet self.assertEqual('Richard Starkey', BandMember.objects.get(id=ringo_id).name) self.assertEqual('George Harrison', updated_members[1].name) self.assertFalse(updated_members[1].id) # no ID yet
def test_can_create_cluster(self): beatles = Band(name='The Beatles') self.assertEqual(0, beatles.members.count()) beatles.members = [ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ] # we should be able to query this relation using (some) queryset methods self.assertEqual(2, beatles.members.count()) self.assertEqual('John Lennon', beatles.members.all()[0].name) self.assertEqual('Paul McCartney', beatles.members.filter(name='Paul McCartney')[0].name) self.assertEqual('Paul McCartney', beatles.members.get(name='Paul McCartney').name) self.assertRaises(BandMember.DoesNotExist, lambda: beatles.members.get(name='Reginald Dwight')) self.assertRaises(BandMember.MultipleObjectsReturned, lambda: beatles.members.get()) self.assertEqual([('Paul McCartney',)], beatles.members.filter(name='Paul McCartney').values_list('name')) self.assertEqual(['Paul McCartney'], beatles.members.filter(name='Paul McCartney').values_list('name', flat=True)) # quick-and-dirty check that we can invoke values_list with empty args list beatles.members.filter(name='Paul McCartney').values_list() self.assertTrue(beatles.members.filter(name='Paul McCartney').exists()) self.assertFalse(beatles.members.filter(name='Reginald Dwight').exists()) self.assertEqual('John Lennon', beatles.members.first().name) self.assertEqual('Paul McCartney', beatles.members.last().name) self.assertTrue('John Lennon', beatles.members.order_by('name').first()) self.assertTrue('Paul McCartney', beatles.members.order_by('-name').first()) # these should not exist in the database yet self.assertFalse(Band.objects.filter(name='The Beatles').exists()) self.assertFalse(BandMember.objects.filter(name='John Lennon').exists()) beatles.save() # this should create database entries self.assertTrue(Band.objects.filter(name='The Beatles').exists()) self.assertTrue(BandMember.objects.filter(name='John Lennon').exists()) john_lennon = BandMember.objects.get(name='John Lennon') beatles.members = [john_lennon] # reassigning should take effect on the in-memory record self.assertEqual(1, beatles.members.count()) # but not the database self.assertEqual(2, Band.objects.get(name='The Beatles').members.count()) beatles.save() # now updated in the database self.assertEqual(1, Band.objects.get(name='The Beatles').members.count()) self.assertEqual(1, BandMember.objects.filter(name='John Lennon').count()) # removed member should be deleted from the db entirely self.assertEqual(0, BandMember.objects.filter(name='Paul McCartney').count()) # queries on beatles.members should now revert to SQL self.assertTrue(beatles.members.extra(where=["tests_bandmember.name='John Lennon'"]).exists())
def test_queryset_exclude_filtering(self): beatles = Band(name='The Beatles', members=[ BandMember(id=1, name='John Lennon'), BandMember(id=2, name='Paul McCartney'), ]) self.assertEqual(1, beatles.members.exclude(name='Paul McCartney').count()) self.assertEqual('John Lennon', beatles.members.exclude(name='Paul McCartney').first().name)
def test_deserialize_json(self): beatles = Band.from_json( '{"pk": 9, "albums": [], "name": "The Beatles", "members": [{"pk": null, "name": "John Lennon", "band": null}, {"pk": null, "name": "Paul McCartney", "band": null}]}' ) self.assertEqual(9, beatles.id) self.assertEqual('The Beatles', beatles.name) self.assertEqual(2, beatles.members.count()) self.assertEqual(BandMember, beatles.members.all()[0].__class__)
def test_saved_items(self): class BandForm(ClusterForm): class Meta: model = Band beatles = Band(name='The Beatles', members=[ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ]) beatles.save() member0, member1 = beatles.members.all() self.assertTrue(member0.id) self.assertTrue(member1.id) form = BandForm({ 'name': "The New Beatles", 'members-TOTAL_FORMS': 4, 'members-INITIAL_FORMS': 2, 'members-MAX_NUM_FORMS': 1000, 'members-0-name': member0.name, 'members-0-DELETE': 'members-0-DELETE', 'members-0-id': member0.id, 'members-1-name': member1.name, 'members-1-id': member1.id, 'members-2-name': 'George Harrison', 'members-2-id': '', 'members-3-name': '', 'members-3-id': '', 'albums-TOTAL_FORMS': 0, 'albums-INITIAL_FORMS': 0, 'albums-MAX_NUM_FORMS': 1000, }, instance=beatles) self.assertTrue(form.is_valid()) form.save() new_beatles = Band.objects.get(id=beatles.id) self.assertEqual('The New Beatles', new_beatles.name) self.assertTrue(BandMember.objects.filter(name='George Harrison').exists()) self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())
def test_save_commit_true(self): john = BandMember(name='John Lennon') paul = BandMember(name='Paul McCartney') ringo = BandMember(name='Richard Starkey') beatles = Band(name='The Beatles', members=[john, paul, ringo]) beatles.save() john_id, paul_id, ringo_id = john.id, paul.id, ringo.id self.assertTrue(john_id) self.assertTrue(paul_id) band_members_formset = self.BandMembersFormset( { 'form-TOTAL_FORMS': 4, 'form-INITIAL_FORMS': 3, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'John Lennon', 'form-0-DELETE': 'form-0-DELETE', 'form-0-id': john_id, 'form-1-name': 'Paul McCartney', 'form-1-id': paul_id, 'form-2-name': 'Ringo Starr', # changing data of an existing record 'form-2-id': ringo_id, 'form-3-name': '', 'form-3-id': '', }, queryset=beatles.members.all()) self.assertTrue(band_members_formset.is_valid()) updated_members = band_members_formset.save() self.assertEqual(1, len(updated_members)) self.assertEqual('Ringo Starr', updated_members[0].name) self.assertEqual(ringo_id, updated_members[0].id) self.assertFalse(BandMember.objects.filter(id=john_id).exists()) self.assertEqual('Paul McCartney', BandMember.objects.get(id=paul_id).name) self.assertEqual(beatles.id, BandMember.objects.get(id=paul_id).band_id) self.assertEqual('Ringo Starr', BandMember.objects.get(id=ringo_id).name) self.assertEqual(beatles.id, BandMember.objects.get(id=ringo_id).band_id)
def test_saved_items_with_non_db_relation(self): class BandForm(ClusterForm): class Meta: model = Band fields = ['name'] john = BandMember(name='John Lennon') paul = BandMember(name='Paul McCartney') beatles = Band(name='The Beatles', members=[john, paul]) beatles.save() # pack and unpack the record so that we're working with a non-db-backed queryset new_beatles = Band.from_json(beatles.to_json()) form = BandForm({ 'name': "The New Beatles", 'members-TOTAL_FORMS': 4, 'members-INITIAL_FORMS': 2, 'members-MAX_NUM_FORMS': 1000, 'members-0-name': john.name, 'members-0-DELETE': 'members-0-DELETE', 'members-0-id': john.id, 'members-1-name': paul.name, 'members-1-id': paul.id, 'members-2-name': 'George Harrison', 'members-2-id': '', 'members-3-name': '', 'members-3-id': '', 'albums-TOTAL_FORMS': 0, 'albums-INITIAL_FORMS': 0, 'albums-MAX_NUM_FORMS': 1000, }, instance=new_beatles) self.assertTrue(form.is_valid()) form.save() new_beatles = Band.objects.get(id=beatles.id) self.assertEqual('The New Beatles', new_beatles.name) self.assertTrue(BandMember.objects.filter(name='George Harrison').exists()) self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())
def test_can_create_formset(self): beatles = Band(name='The Beatles', members=[ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ]) band_members_formset = self.BandMembersFormset(queryset=beatles.members.all()) self.assertEqual(5, len(band_members_formset.forms)) self.assertEqual('John Lennon', band_members_formset.forms[0].instance.name)
def test_saved_items(self): class BandForm(ClusterForm): class Meta: model = Band fields = ['name'] john = BandMember(name='John Lennon') paul = BandMember(name='Paul McCartney') beatles = Band(name='The Beatles', members=[john, paul]) beatles.save() self.assertTrue(john.id) self.assertTrue(paul.id) form = BandForm({ 'name': "The New Beatles", 'members-TOTAL_FORMS': 4, 'members-INITIAL_FORMS': 2, 'members-MAX_NUM_FORMS': 1000, 'members-0-name': john.name, 'members-0-DELETE': 'members-0-DELETE', 'members-0-id': john.id, 'members-1-name': paul.name, 'members-1-id': paul.id, 'members-2-name': 'George Harrison', 'members-2-id': '', 'members-3-name': '', 'members-3-id': '', 'albums-TOTAL_FORMS': 0, 'albums-INITIAL_FORMS': 0, 'albums-MAX_NUM_FORMS': 1000, }, instance=beatles) self.assertTrue(form.is_valid()) form.save() new_beatles = Band.objects.get(id=beatles.id) self.assertEqual('The New Beatles', new_beatles.name) self.assertTrue(BandMember.objects.filter(name='George Harrison').exists()) self.assertFalse(BandMember.objects.filter(name='John Lennon').exists())
def test_save_commit_true(self): john = BandMember(name='John Lennon') paul = BandMember(name='Paul McCartney') ringo = BandMember(name='Richard Starkey') beatles = Band(name='The Beatles', members=[ john, paul, ringo ]) beatles.save() john_id, paul_id, ringo_id = john.id, paul.id, ringo.id self.assertTrue(john_id) self.assertTrue(paul_id) band_members_formset = self.BandMembersFormset({ 'form-TOTAL_FORMS': 4, 'form-INITIAL_FORMS': 3, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'John Lennon', 'form-0-DELETE': 'form-0-DELETE', 'form-0-id': john_id, 'form-1-name': 'Paul McCartney', 'form-1-id': paul_id, 'form-2-name': 'Ringo Starr', # changing data of an existing record 'form-2-id': ringo_id, 'form-3-name': '', 'form-3-id': '', }, queryset=beatles.members.all()) self.assertTrue(band_members_formset.is_valid()) updated_members = band_members_formset.save() self.assertEqual(1, len(updated_members)) self.assertEqual('Ringo Starr', updated_members[0].name) self.assertEqual(ringo_id, updated_members[0].id) self.assertFalse(BandMember.objects.filter(id=john_id).exists()) self.assertEqual('Paul McCartney', BandMember.objects.get(id=paul_id).name) self.assertEqual(beatles.id, BandMember.objects.get(id=paul_id).band_id) self.assertEqual('Ringo Starr', BandMember.objects.get(id=ringo_id).name) self.assertEqual(beatles.id, BandMember.objects.get(id=ringo_id).band_id)
def test_deserialize_with_multiple_sort_order(self): Album._meta.ordering = ['sort_order', 'name'] beatles = Band.from_json('{"pk": null, "albums": [{"pk": 1, "name": "With The Beatles", "sort_order": 1}, {"pk": 2, "name": "Please Please Me", "sort_order": 1}, {"pk": 3, "name": "Please Please Me", "sort_order": 2}], "name": "The Beatles", "members": []}') Album._meta.ordering = ['sort_order'] self.assertEqual(3, beatles.albums.count()) # Make sure the albums were ordered correctly self.assertEqual(2, beatles.albums.all()[0].pk) self.assertEqual(1, beatles.albums.all()[1].pk) self.assertEqual(3, beatles.albums.all()[2].pk)
def test_cluster_form_without_formsets(self): class BandForm(ClusterForm): class Meta: model = Band formsets = () fields = ['name'] beatles = Band(name='The Beatles') beatles.save() form = BandForm({ 'name': "The New Beatles", }, instance=beatles) self.assertTrue(form.is_valid()) form.save(commit=False) self.assertEqual(1, Band.objects.filter(name='The Beatles').count()) beatles.save() self.assertEqual(0, Band.objects.filter(name='The Beatles').count())
def test_deserialize(self): beatles = Band.from_serializable_data({ 'pk': 9, 'albums': [], 'name': 'The Beatles', 'members': [ {'pk': None, 'name': 'John Lennon', 'band': None}, {'pk': None, 'name': 'Paul McCartney', 'band': None}, ] }) self.assertEqual(9, beatles.id) self.assertEqual('The Beatles', beatles.name) self.assertEqual(2, beatles.members.count()) self.assertEqual(BandMember, beatles.members.all()[0].__class__)
def test_queryset_filtering(self): beatles = Band(name='The Beatles', members=[ BandMember(id=1, name='John Lennon'), BandMember(id=2, name='Paul McCartney'), ]) self.assertEqual('Paul McCartney', beatles.members.get(id=2).name) self.assertEqual('Paul McCartney', beatles.members.get(id='2').name) self.assertEqual(1, beatles.members.filter(name='Paul McCartney').count()) # also need to be able to filter on foreign fields that return a model instance # rather than a simple python value self.assertEqual(2, beatles.members.filter(band=beatles).count()) # and ensure that the comparison is not treating all unsaved instances as identical rutles = Band(name='The Rutles') self.assertEqual(0, beatles.members.filter(band=rutles).count()) # and the comparison must be on the model instance's ID where available, # not by reference beatles.save() beatles.members.add(BandMember(id=3, name='George Harrison')) # modify the relation so that we're not to a plain database-backed queryset also_beatles = Band.objects.get(id=beatles.id) self.assertEqual(3, beatles.members.filter(band=also_beatles).count())
def test_model_with_zero_pk(self): beatles = Band(name='The Beatles', members=[ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ]) beatles.save() beatles.pk = 0 beatles.members.commit() beatles.save() self.assertEqual(Band.objects.get(pk=0).name, 'The Beatles')
def test_integrity_error_with_none_pk(self): beatles = Band(name='The Beatles', members=[ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ]) beatles.save() beatles.pk = None self.assertRaises(IntegrityError, lambda: beatles.members.commit()) # this should work fine, as Django will end up cloning this entity beatles.save() self.assertEqual(Band.objects.get(pk=beatles.pk).name, 'The Beatles')
def test_save_with_update_fields(self): beatles = Band(name='The Beatles', members=[ BandMember(name='John Lennon'), BandMember(name='Paul McCartney'), ], albums=[ Album(name='Please Please Me', sort_order=1), Album(name='With The Beatles', sort_order=2), Album(name='Abbey Road', sort_order=3), ]) beatles.save() # modify both relations, but only commit the change to members beatles.members.clear() beatles.albums.clear() beatles.name = 'The Rutles' beatles.save(update_fields=['name', 'members']) updated_beatles = Band.objects.get(pk=beatles.pk) self.assertEqual(updated_beatles.name, 'The Rutles') self.assertEqual(updated_beatles.members.count(), 0) self.assertEqual(updated_beatles.albums.count(), 3)
def test_deserialize_json(self): beatles = Band.from_json('{"pk": 9, "albums": [], "name": "The Beatles", "members": [{"pk": null, "name": "John Lennon", "band": null}, {"pk": null, "name": "Paul McCartney", "band": null}]}') self.assertEqual(9, beatles.id) self.assertEqual('The Beatles', beatles.name) self.assertEqual(2, beatles.members.count()) self.assertEqual(BandMember, beatles.members.all()[0].__class__)