I have a Model in Django. It has a Group and inside the group are Cameras.
class Groups(models.Model):
groupName = models.CharField(max_length=255)
class Cameras(models.Model):
group = models.ForeignKey(Groups)
cameraID = models.IntegerField()
When I try to remove a Camera or set of cameras in the model.
camera = Cameras.objects.filter(cameraID=int(camID))
camera.delete()
It removes any camera with an ID Greater than 0. But If I have a camera ID of '0' It fails to remove. Any ideas why this would be.
2 Answers 2
When you are using filter, you can get 0 or multiple objects returned, unlike get which will only return 1 object, or cause errors.
If you want to delete every objects which is returned from a filter, you can iterate over it like so:
cameras = Cameras.objects.filter(cameraID=int(camID))
## let's say this returns [<Camera:1>,<Camera:2>]
for camera in cameras:
camera.delete()
## this loop will delete each object in the query
4 Comments
.delete() method as well: docs.djangoproject.com/en/1.2/ref/models/querysets/#delete if x != None: instead of if not x:. Lesson learned.Try use camera = Cameras.objects.get(pk=camID) then you know for sure you've only got one object. You can then camera.delete()
You also don't need all the ';' characters in your code.
1 Comment
pk for the Camera is not the cameraID, just FYI. Agree with the ';' comment. Cleaning up the example now.
Cameras.objects.filter(cameraID=0).delete()from a shell?