Issue #16 Se crea la entidad en caso que no exista al agregarla a una lista
This commit is contained in:
@@ -1,6 +1,12 @@
|
||||
from django import forms
|
||||
|
||||
from lists.models import ListItem, Tag
|
||||
from lists.models import ListItem, Tag, Entity
|
||||
|
||||
|
||||
class EntityForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Entity
|
||||
fields = ['mbid', 'entity_type']
|
||||
|
||||
|
||||
class ListItemForm(forms.ModelForm):
|
||||
|
||||
@@ -67,6 +67,30 @@ class TestList(TestCase):
|
||||
def test_add_to_list(self):
|
||||
to_add = {
|
||||
'entity': 'b',
|
||||
'entity_type': 'artist',
|
||||
'tags': ['1', '2']
|
||||
}
|
||||
|
||||
response = self.client.post('/api/lists/list/1/', json.dumps(to_add),
|
||||
content_type='application/json',
|
||||
HTTP_AUTHORIZATION=self._user_bearer_token())
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
list_item = ListItem.objects.filter(pk=2)
|
||||
|
||||
self.assertEqual(list_item.count(), 1)
|
||||
|
||||
list_item = list_item[0]
|
||||
|
||||
self.assertEqual(list_item.user_id, self.user.id)
|
||||
self.assertEqual(list_item.entity_id, to_add['entity'])
|
||||
self.assertEqual(list_item.tags.count(), len(to_add['tags']))
|
||||
|
||||
def test_add_to_list_non_exists_entity(self):
|
||||
to_add = {
|
||||
'entity': 'd',
|
||||
'entity_type': 'artist',
|
||||
'tags': ['1', '2']
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ from json.decoder import JSONDecodeError
|
||||
from django.http import JsonResponse
|
||||
from oauth2_provider.decorators import protected_resource
|
||||
|
||||
from lists.forms import ListItemForm, TagForm
|
||||
from lists.models import ListItem, Tag
|
||||
from lists.forms import ListItemForm, TagForm, EntityForm
|
||||
from lists.models import ListItem, Tag, Entity
|
||||
from users.models import User
|
||||
|
||||
|
||||
@@ -124,6 +124,20 @@ def _add_to_list(request, user):
|
||||
|
||||
list_item = ListItem(user=user)
|
||||
|
||||
if request_data.get('entity') and Entity.objects.filter(mbid=request_data['entity']).count() == 0:
|
||||
# Entity no existe en la base de datos, se crea
|
||||
data = {
|
||||
'mbid': request_data.get('entity', None),
|
||||
'entity_type': request_data.get('entity_type', None)
|
||||
}
|
||||
|
||||
entity_form = EntityForm(data)
|
||||
|
||||
if not entity_form.is_valid():
|
||||
return JsonResponse({'status': 400, 'error': entity_form.errors.as_json()}, status=400)
|
||||
|
||||
entity_form.save()
|
||||
|
||||
form = ListItemForm(request_data, instance=list_item)
|
||||
|
||||
if not form.is_valid():
|
||||
|
||||
Reference in New Issue
Block a user