模型中存储列表的最有效方法是什么

模型中存储列表的最有效方法是什么

本文介绍了在 Django 模型中存储列表的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我的代码中有很多 python 对象,类似于以下内容:

Currently I have a lot of python objects in my code similar to the following:

class MyClass():
  def __init__(self, name, friends):
      self.myName = name
      self.myFriends = [str(x) for x in friends]

现在我想把它变成一个 Django 模型,其中 self.myName 是一个字符串字段,self.myFriends 是一个字符串列表.

Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.

from django.db import models

class myDjangoModelClass():
    myName = models.CharField(max_length=64)
    myFriends = ??? # what goes here?

由于列表是 Python 中的一种常见数据结构,我有点期望有一个 Django 模型字段.我知道我可以使用 ManyToMany 或 OneToMany 关系,但我希望在代码中避免这种额外的间接性.

Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.

我添加了这个 相关问题,人们可能会觉得有用.

I added this related question, which people may find useful.

推荐答案

将这种关系表示为 Friends 表的一对多外键关系不是更好吗?我知道 myFriends 只是字符串,但我认为更好的设计是创建一个 Friend 模型并让 MyClass 包含一个外键与结果表的关系.

Would this relationship not be better expressed as a one-to-many foreign key relationship to a Friends table? I understand that myFriends are just strings but I would think that a better design would be to create a Friend model and have MyClass contain a foreign key realtionship to the resulting table.

这篇关于在 Django 模型中存储列表的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:28