在Django模型中存储列表的最有效方法是什么? [英] What is the most efficent way to store a list in the Django models?

查看:1224
本文介绍了在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是一个字符串列表。 p>

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 只是字符串,但我认为更好的设计是创建一个朋友模型,并有 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模型中存储列表的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆