Django save model ForeignKey attitude

in my model.py

class Layer(models.Model): user = models.IntegerField() name = models ... class Point(models.Model): layers = models.ForeignKey(Layer) meta = models.TextField() ... 

on my view.py

 def datasave(request, id): mid = request.POST.get("layerid",default = "") metas = request.POST.get("meta",default = "") cs = Point() cs.layers = mid cs.meta = metas cs.save() 

but it gives an error in my django debugging .. in my project I use geodjango, openlayers and extjs ... I did not find a solution to save my message

I did not do any relationship with my external key. Basically I want to make a layer, than when I want to add a point to my layer, I want to save my point with the layer ID ....

+7
source share
2 answers

It is helpful to post a trace to help understand your problem (for future questions).

It seems to me that you are passing a number to your Point instance layers attribute, which would raise a ValueError . The only place you can pass a number to a foreign key field is in the django form, which does a search for you.

Instead, you need to assign the actual instance of Layer .

 cs = Point() cs.layers = Layer.objects.get(id=mid) cs.meta = metas cs.save() 
+8
source

A more efficient way is to specify a foreign key by adding "_id" at the end, for example:

 cs = Point(layers_id = mid, meta = metas) cs.save() 

DO NOT run layers = XXX.objects.get (id = ###), as this doubles the number of database queries.

ALSO ... you are not clearing the POST data here, which is pretty dangerous. Get it like this:

 from django import forms id_field = forms.IntegerField() layer_id = id_field.clean(request.POST.get("layerId", "") 
+13
source

All Articles