简体   繁体   English

将模型添加到Django外键

[英]Adding Models to Django Foreign Key

I have a model with a foreign key, allowing me to reference an arbitrary amount of other models. 我有一个带有外键的模型,允许我引用任意数量的其他模型。 So I can add and remove using the admin interface, but how can I do the equivalent programatically? 因此,我可以使用管理界面进行添加和删除,但是如何以编程方式进行等效操作?

class Json(models.Model):
    data = models.TextField()

class Dweet(models.Model):
    name = models.CharField(max_length = 300)
    data = models.ForeignKey(Json)

在此处输入图片说明

In order to use those models you can do the following: 为了使用这些模型,您可以执行以下操作:

>>> from app.models import Json, Dweet
>>> a = Json(data="asdf")
>>> a.save()
>>> b = Dweet(name="Test", data=a)
>>> b.save()
>>> c = Dweet(name="Test2", data=a)
>>> c.save()

After that you end up with one Json object and two Dweet objects that both point to said Json object. 之后,您将获得一个Json对象和两个Dweet对象,这两个对象均指向所述Json对象。 That's about as interesting as it gets with the two models you've shown us. 这和您展示给我们的两个模型一样有趣。 You can add more Json objects if you like of course, but each Dweet can only point to one Json (not sure if you were asking for something different in your question). 当然,您可以添加更多Json对象,但是每个Dweet只能指向一个Json(不确定您是否在询问其他问题)。

Its not clear what your problem is by the description provided but i would try to answer on the basis of what i can understand through the snapshot. 通过提供的描述尚不清楚您的问题是什么,但是我会根据我可以通过快照理解的内容来尝试回答。

Actually one option is not listed twice in drop down rather it represents two model objects stored in Json table, ie as u have specified Json as foreign key. 实际上,一个选项没有在下拉列表中列出两次,而是代表了存储在Json表中的两个模型对象,即,由于您已将Json指定为外键。 so each time you load the form it will request a queryset (like select * from Json). 因此,每次加载表单时,它都会请求一个查询集(例如,来自Json的select *)。 so in response it will receive model objects(Number of distinct rows in respective model table). 因此,作为响应,它将接收模型对象(相应模型表中不同行的数量)。 So You need to specify a unicode () method in order to display object attribute value on the place of just Json Object . 因此,您需要指定unicode ()方法,以便仅在Json Object的位置显示对象属性值。 So If you write a method like 因此,如果您编写类似

class Json(models.Model):
    data = models.TextField()

    def __unicode__(self):
    return self.data   

You will get the data stored in Model object ie data . 您将获得存储在Model对象中的数据,即data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM