简体   繁体   中英

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

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. so each time you load the form it will request a queryset (like select * from Json). 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 . 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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