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

2024-04-30 03:59:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为一个媒体对象保存x个媒体流。所以我在这里有一个一对多的关系(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时-清除结果['streams']['index']

提前谢谢


Tags: namenewforstreamindexvaluetypechannel
3条回答

我清理了您的解决方案,因为您正在调用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不存在,则返回none。有关StackOverflow的解释,请参见here

请参见here,了解objects.create()上的Django文档,它也调用save

您需要遍历dict项

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()

相关问题 更多 >