Django 如何将对象保存在列表的 for 循环中

Django how to save objects in a for loop from list

我想为一个媒体对象保存 x 个 MediaStreams。所以我在这里有一个一对多关系(ForeignKey),但我不确定我如何工作,因为目前总是保存相同的流,而不是预期的 5 个不同的流。我需要在哪里放置“i”才能在 for 循环中创建对象?

for i in clean_result['streams']:
    new_stream = MediaStreams.objects.create(index=index_value, stream_bitrate=streambitrate_value,
                                               codec_name=codec_name_value, codec_type=codec_type_value,
                                               width=width_value, height=height_value,
                                               channel_layout=channel_layout_value, language=language_value,
                                               media=new_object)
    new_stream.save()

目前仅保存索引 5 而不是 0-5 - clean_result['streams']['index'].

提前致谢

您需要遍历字典项。

dict_ = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
>>> for item in dict_.items():
...     print(item)
...
# output will be like this:
('color', 'blue')
('fruit', 'apple')
('pet', 'dog')  

你的情况:

for i in clean_result['streams'].items():
    # do your stuff  

如果您想了解更多有关如何在 python 中遍历字典的信息,请查看此 link

得到这样的效果:

for i in clean_result['streams']:
    if 'index' in i:
        index_value = i['index']
    if 'bit_rate' in i:
        streambitrate_value = i['bit_rate']
    if 'codec_name' in i:
        codec_name_value = i['codec_name']
    if 'codec_type' in i:
        codec_type_value = i['codec_type']
    if 'width' in i:
        width_value = i['width']
    if 'height' in i:
        height_value = i['height']
    if 'channel_layout' in i:
        channel_layout_value = i['channel_layout']
    if 'tags' in i and 'language' in i['tags']:
        language_value = i['tags']['language']
    new_stream = MediaStreams.objects.create(index=index_value, stream_bitrate=streambitrate_value,
                                             codec_name=codec_name_value, codec_type=codec_type_value,
                                             width=width_value, height=height_value,
                                             channel_layout=channel_layout_value, language=language_value,
                                             media=new_object)
    new_stream.save()

我清理了你的解决方案,因为你正在调用 objects.create(),你不需要调用 save()。此外,由于您期望 clean_result['streams'] 中的值存在,您可以执行以下操作:

for i in clean_result['streams']:
    MediaStreams.objects.create(
        index=i['index'],
        stream_bitrate=i['bit_rate'],
        codec_name=i['codec_name'],
        codec_type=i['codec_type'],
        width=i['width'],
        height=i['height'],
        channel_layout=i['channel_layout'],
        language=i['tags']['language'],
        media=new_object
    )

如果值可能不存在,您可以使用 i.get('index'),如果 index 不存在,则可以使用 returns none。有关 Whosebug 上的 dict.get() 解释,请参阅 here

有关 objects.create() 的 Django 文档,请参阅 here,它也调用保存。