doableware / djongo

Django and MongoDB database connector
https://www.djongomapper.com
GNU Affero General Public License v3.0
1.86k stars 352 forks source link

is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string #627

Open shirke95 opened 2 years ago

shirke95 commented 2 years ago

One line description of the issue

is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string

Python script

```python class BaseFields(models.Model): _id = models.ObjectIdField(unique=True) name = models.CharField(max_length=200, blank=False) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True class Project(BaseFields): code = models.CharField( max_length=5, unique=True, blank=False, validators=[RegexValidator("^[A-Z0-9]*$", "only UPPERCASE letter are allowed")], ) cg_supervisor = models.ForeignKey( to=User, null=True, on_delete=models.DO_NOTHING, related_name="cg_supervisor" ) start_date = models.DateField(auto_now_add=True) entity_type = models.CharField(max_length=20, default="Project") duration = models.IntegerField(default=1) due_date = models.DateField(blank=True) resolution = models.CharField( max_length=9, validators=[RegexValidator("^\d{1,4}X\d{1,4}$", "Enter valid resolution")], ) start_frame = models.IntegerField(default=101) fps = models.FloatField(default=24.0) is_episodic = models.BooleanField(default=True) is_active = models.BooleanField(default=True) local_path = models.CharField(max_length=200, blank=True) thumbnail = models.ImageField( default="project_thumbnails/default.jpg", upload_to="project_thumbnails" ) users = models.ManyToManyField(to=User, blank=True) def __str__(self): return f"Project {self._id}" def save(self, *args, **kwargs): if not self._id: self._id = self.code.lower() super(Project, self).save(*args, **kwargs) ``` Django==3.2.14 djongo==1.3.6 pymongo==3.12.3 #### Traceback ![image](https://user-images.githubusercontent.com/28471615/179480537-4f72ae62-4a63-4ee6-84f1-0a20446b440f.png)
shirke95 commented 2 years ago

i want save custom _id field

keder-code-hash commented 1 year ago

Hey first of all remove id filed for abstract model class. It actually conflicts the property of modelling. Put this id field into the Projects model. And you can use the ObjectIdField from bson. Actually in djongo bson ObjectIdField is used internally. Hope this resolve your issue.

keder-code-hash commented 1 year ago

If you use serializers make sure that you have put id fields as a read_only one. Otherwise it will receive the wrong value.