Somehow I can't manage to add a feature to my PostgreSQL layer. Is this only possible in edit mode?
My layer
>>> cp
<qgis._core.QgsVectorLayer object at 0x7f541c0e0348>
>>> cp.source()
u'dbname=\'work_viewtest\' host=myhost port=5432 user=\'b\' password=\'bxxxxxx\' key=\'id\' table="public"."v2_calculation_point" (the_geom) sql='
This is how I create my feature
f = QgsFeature()
f.setGeometry(QgsGeometry.fromPoint(QgsPoint(123, 456)))
f.setAttributes([10, 100, "ref", -1])
cp.dataProvider().addFeatures([f])
(True, [<qgis._core.QgsFeature object at 0x7f539ffa33e0>])
cp.updateExtents()
cp.updateFields()
The addFeatures()
method returns True
but I don't see any features in my layer, nor in the database table itself.
2 Answers 2
In case anyone stumbles across a similar problem. It seems as if the data provider does not check for insert errors in the database itself or least not for certain error types like foreign key constraints.
When I try to insert the data provided in my question by SQL:
INSERT INTO v2_calculation_point (id, content_type_id
, user_ref
, calc_type
, the_geom)
VALUES
(DEFAULT, 10, 'ref', -1, ST_GeomFromText('POINT(123 456)',28992))
;
I get the following error
ERROR: insert or update on table "v2_calculation_point" violates
foreign key constraint "content_type_id_refs_id_522d7533"
After removing the constraint I can also add data like so (without startEditing()
)
cp.dataProvider().addFeatures([f])
(True, [<qgis._core.QgsFeature object at 0x7fcece585a68>])
f = QgsFeature()
f.setGeometry(QgsGeometry.fromPoint(QgsPoint(123, 555)))
f.setAttributes([77, 199, "ref-new", 5])
cp.dataProvider().addFeatures([f])
(True, [<qgis._core.QgsFeature object at 0x7fcece585b00>])
I also had the same problem, what I did to solve it is; in the postgres table where the record is taken, add a geometric column. and ready, it was solved without removing the primary key,
Explore related questions
See similar questions with these tags.
cp.startEditing()
) before you commit any changes (cp.commitChanges()
).True
too but still no data in my layer....setAttributes()
does not exist in the reference relation. Still strange that theaddFeatures()
method returns True.True
because it has successfully copied the feature regardless if it has been committed.