«<Model: ModelInstance>» должно иметь значение для поля «id», прежде чем можно будет использовать эту связь «многие ко мPython

Программы на Python
Гость
«<Model: ModelInstance>» должно иметь значение для поля «id», прежде чем можно будет использовать эту связь «многие ко м

Сообщение Гость »

В настоящее время возникает эта ошибка между моей моделью UserProfile и моделью Song, когда я пытаюсь получить все пользовательские песни "song = user_prof.songs.all()", и ошибкой является заголовок " . Я впервые использую сквозную модель для двух моделей (Song и Note) и у меня есть подозрения. UserProfile, Song, Notes и SongNotes > все экземпляры сохранены и доступны для просмотра в администраторе django, однако song_instance не показывает никаких примечаний, на самом деле он даже не показывает поле примечаний, я думаю, из-за сквозного.
Просмотр песни

Код: Выделить всё

class Songs(APIView):
def post(self, request, format=None):
try:
data = self.request.data

user_song = data['song']
name = data['name']

user = self.request.user
user_prof = UserProfile.objects.get(user=user)

song_instance = Song.objects.create(name=name)

user_prof.songs.add(song_instance)
user_prof.save()

for index, pair in enumerate(user_song):
note = Note.objects.create(note=pair[0], timestamp=pair[1])
song_note_through = SongNote.objects.create(song=song_instance, note=note, order=index)

song_instance.save()
return Response({ 'success': 'Song created' })

except Exception as e:
print('Songs:post ', e, file=sys.stderr)
return Response({ 'error': 'Unable to create song' })

def get(self, request, id='all', format=None):
try:
if id == 'all':
user = self.request.user
user_prof = UserProfile(user=user)
song = user_prof.songs.all()
else:
song = Song.objects.get(id=id)

serializer = SongSerializer(song)

return Response({ 'song': serializer.data})
except Exception as e:
print('Songs:get ', e, file=sys.stderr)
return Response({ 'error':  'Unable to get song' })
models.py

Код: Выделить всё

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=255, default='')
last_name = models.CharField(max_length=255, default='')
posts = models.ManyToManyField('Post', blank=True, related_name='created_post')
songs = models.ManyToManyField('Song', blank=True)

class Song(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100)
notes = models.ManyToManyField('Note', through='SongNote', blank=True)

class Note(models.Model):
note = models.CharField(max_length=500)
timestamp = models.IntegerField(default=0)

class SongNote(models.Model):
song = models.ForeignKey(Song, on_delete=models.CASCADE)
note = models.ForeignKey(Note, on_delete=models.CASCADE)
order = models.IntegerField()

class Meta:
ordering = ['order']
обратная трассировка:

Код: Выделить всё

Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\wsgiref\handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 80, in __call__
return self.application(environ, start_response)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\wsgi.py", line 124, in __call__
response = self.get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\base.py", line 140, in get_response
response = self._middleware_chain(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
response = response_for_exception(request, exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
response = handle_uncaught_exception(
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\corsheaders\middleware.py", line 56, in __call__
result = self.get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
response = response_for_exception(request, exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
response = handle_uncaught_exception(
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\utils\deprecation.py", line 134, in __call__
response = response or self.get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
response = response_for_exception(request, exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
response = handle_uncaught_exception(
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\utils\deprecation.py", line 134, in __call__
response = response or self.get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
response = response_for_exception(request,  exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
response = handle_uncaught_exception(
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\utils\deprecation.py", line 134, in __call__
response = response or self.get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
response = response_for_exception(request, exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
response = handle_uncaught_exception(
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\utils\deprecation.py", line 134, in __call__
response = response or self.get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
response = response_for_exception(request, exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
response = handle_uncaught_exception(
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\utils\deprecation.py", line 134, in __call__
response = response or self.get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
response = response_for_exception(request, exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
response = handle_uncaught_exception(
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\utils\deprecation.py", line 134, in __call__
response = response or self.get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
response = response_for_exception(request, exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
response = handle_uncaught_exception(
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\utils\deprecation.py", line 134, in __call__
response = response or self.get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
response = response_for_exception(request, exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
response = handle_uncaught_exception(
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\core\handlers\base.py", line 197,  in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\views\decorators\csrf.py", line 65, in _view_wrapper
return view_func(request, *args, **kwargs)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\views\generic\base.py", line 104, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebsite\sheetmusic\views.py", line 400, in get
song = user_prof.songs
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 650, in __get__
return self.related_manager_cls(instance)
File "C:\Users\19494\Desktop\Coding\Python\SheetMusicWeb\SheetMusicWebvenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1069, in __init__
raise ValueError(
ValueError: "" needs to have a value for field "id" before this many-to-many relationship can be used.
Я некоторое время оглядывался вокруг. Есть еще одна тема с этим вопросом, но это не помогло. Большинство предположений заключаются в том, что мне не удалось сохранить модель песни перед доступом к ее атрибутам, но я вижу, что они находятся в панели администратора.

Подробнее здесь: https://stackoverflow.com/questions/781 ... his-many-t

Вернуться в «Python»