MongoEngine: Embeddeddocument fields do not take default value as none? - python

I've set the default values for fields in embedded document but when I try to post data it doesn't accept None or Blank values.
Here is what my code looks like-
models.py
class MetaData(EmbeddedDocument):
adcode = StringField(max_length=50, default="", blank=True, Null=True)
additional_html_below_header = StringField(max_length=50, default="")
adhoc_plus_disable_pacing = BooleanField(default=False)
adhoc_plus_has_priority = BooleanField(default=False)
adhoc_server = StringField(max_length=50, default="")
class LandingPage(Document):
type = StringField(max_length=50, default="")
meta_clean_URL_tag = StringField(max_length=50, default="")
meta_name = StringField(max_length=50, default="")
created_time = DateTimeField(default=datetime.datetime.now)
new = BooleanField(default=False)
meta_data = EmbeddedDocumentField(MetaData)
serializers.py
class MetaDataSerializer(serializers.EmbeddedDocumentSerializer):
class Meta:
model = MetaData
class LandingPageSerializer(serializers.DocumentSerializer):
meta_data = MetaDataSerializer()
class Meta:
model = LandingPage
Is there anything wrong I'm doing here?

class MetaDataSerializer(serializers.EmbeddedDocumentSerializer):
adcode = serializers.CharField(allow_blank=True,allow_null=True)
adhoc_server = serializes.CharField(allow_blank=True,allow_null=True)
additional_html_below_header = serializers.CharField(allow_blank=True,allow_null=True)
class Meta:
model = MetaData
DRF-mongoengine or for that matter DRF does not allow null and blank values for strings. They need to be explicitly mentioned. The bounds imposed on models do not hold inside serializers.
The above mentioned change should help you maintain the validations as required by you.

Related

django getting all objects from select

I also need the field (commentGroupDesc) from the foreign keys objects.
models.py
class commentGroup (models.Model):
commentGroup = models.CharField(_("commentGroup"), primary_key=True, max_length=255)
commentGroupDesc = models.CharField(_("commentGroupDesc"),null=True, blank=True, max_length=255)
def __str__(self):
return str(self.commentGroup)
class Meta:
ordering = ['commentGroup']
class Comment (models.Model):
commentID = models.AutoField(_("commentID"),primary_key=True)
commentUser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
commentGroup = models.ForeignKey(commentGroup, on_delete=models.CASCADE, null=True)
commentCI = models.ForeignKey(Servicenow, on_delete=models.CASCADE, null=True)
commentText = RichTextField(_("commentText"), null=True, blank=True)
commentTableUpdated = models.CharField(_("commentTableUpdated"), null=True, blank=True, max_length=25)
def __str__(self):
return str(self.commentGroup)
class Meta:
ordering = ['commentGroup']
views.py
comment = Comment.objects.get(pk=commentID)
Here I get the commentGroup fine but I also need commentGroupDesc to put into my form.
At first, it's not a good thing to name same your model field as model name which is commentGroup kindly change field name, and run migration commands.
You can simply use chaining to get commentGroupDesc, also it's better to use get_object_or_404() so:
comment = get_object_or_404(Comment,pk=commentID)
group_desc = comment.commentGroup.commentGroupDesc
Remember to change field and model name first.

Showing extra field on ManyToMany relationship in Django serializer

I have a ManyToMany field in Django, like this:
class Dictionary(models.Model):
traditional = models.CharField(max_length=50)
simplified = models.CharField(max_length=50)
pinyin_numbers = models.CharField(max_length=50)
pinyin_marks = models.CharField(max_length=50)
translation = models.TextField()
level = models.IntegerField()
frequency = models.IntegerField()
idiom = models.BooleanField()
child_char = models.ManyToManyField('Dictionary', through='DictionaryChildChar', null=True)
class Meta:
db_table = 'dictionary'
indexes = [
models.Index(fields=['simplified', ]),
models.Index(fields=['traditional', ]),
]
class DictionaryChildChar(models.Model):
class Meta:
db_table = 'dictionary_child_char'
from_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="from_dictionary")
to_dictionary = models.ForeignKey(Dictionary, on_delete=models.CASCADE, related_name="to_dictionary")
word_order = models.IntegerField()
Currently, I have a serializer like this:
class FuzzySerializer(serializers.ModelSerializer):
pinyin = serializers.CharField(
required=False, source="pinyin_marks")
definition = serializers.CharField(
required=False, source="translation")
hsk = serializers.CharField(required=False, source="level")
class Meta:
model = Dictionary
fields = ["id", "simplified", "pinyin", "pinyin_numbers","definition", "hsk", "traditional", "child_char"]
depth = 1
This gives me a dictionary entry, as well as the child dictionary entries associated with it (as a Chinese word is made up of several Chinese characters)
However, I need to know what order these child characters are in, and hence why I have word_order.
I would like this word_order field to appear on the individual child_char - how do I write my serializer in such a way that this additional field is present? Would I need to make a separate serializer for child_char?
EDIT: I have tried this serializer, it doesn't work:
class FuzzyChildCharSerializer(serializers.ModelSerializer):
class Meta:
model = DictionaryChildChar
fields = ["word_order"]
Easiest way is to create a dedicated FuzzyChildCharSerializer and then connect it to your original serializer as a nested relationship:
class FuzzyChildCharSerializer():
class Meta:
model = DictionaryChildChar
fields = ["word_order"] # And whatever other fields you want
class FuzzySerializer():
child_char = FuzzyChildCharSerializer(many=True)
...
You could also write a SerializerMethodField.
It appears I had to bridge the connection via the glue table, which makes sense.
class FuzzyChildCharSerializer(serializers.ModelSerializer):
pinyin = serializers.CharField(
required=False, source="pinyin_marks")
definition = serializers.CharField(
required=False, source="translation")
hsk = serializers.CharField(required=False, source="level")
class Meta:
model = Dictionary
fields = ["id", "simplified", "pinyin", "pinyin_numbers","definition", "hsk", "traditional",]
class FuzzyChildCharSerializerGlue(serializers.ModelSerializer):
to_dictionary = FuzzyChildCharSerializer()
class Meta:
model = DictionaryChildChar
fields = '__all__'
class FuzzySerializer(serializers.ModelSerializer):
pinyin = serializers.CharField(
required=False, source="pinyin_marks")
definition = serializers.CharField(
required=False, source="translation")
hsk = serializers.CharField(required=False, source="level")
from_dictionary = FuzzyChildCharSerializerGlue(many=True)
class Meta:
model = Dictionary
fields = ["id", "simplified", "pinyin", "pinyin_numbers","definition", "hsk", "traditional", "from_dictionary"]
depth = 1
This provides each character with its given word order

How can I reach second level natural keys on django query?

I have this models on django with natural_keys functions declared.
class Comments(models.Model):
profile = models.ForeignKey('Profiles', models.DO_NOTHING)
book = models.ForeignKey(Books, models.DO_NOTHING)
date = models.DateTimeField()
text = models.TextField()
class Meta:
managed = False
db_table = 'comments'
class Profiles(models.Model):
alias = models.CharField(max_length=40)
mail = models.CharField(max_length=255)
mainimg = models.ForeignKey(Multimedia, models.DO_NOTHING)
birthdate = models.DateTimeField(blank=True, null=True)
country = models.CharField(max_length=30, blank=True, null=True)
password = models.CharField(max_length=255)
terms = models.IntegerField(blank=True, null=True)
device_token = models.CharField(max_length=500)
def natural_key(self):
return (self.pk, self.alias, self.country, self.mainimg)
class Meta:
managed = False
db_table = 'profiles'
class Multimedia(models.Model):
url = models.CharField(max_length=255)
title = models.CharField(max_length=100)
alt = models.CharField(max_length=150, blank=True, null=True)
description = models.CharField(max_length=150, blank=True, null=True)
mytype = models.CharField(max_length=20, blank=True, null=True)
extension = models.CharField(max_length=6, blank=True, null=True)
def natural_key(self):
return (self.pk, self.url)
class Meta:
managed = False
db_table = 'multimedia'
When I do a get comments query, I want a full response with the comment details, some book details, and profile details (including the picture). Everything goes fine except when I want the profile mainimg being serialized with natural keys.
The error response is
is not JSON serializable
when executing this:
def getcomments(request):
#Book get all comments - returns all comments on a book.
profilelogged = validtoken(request.META['HTTP_MYAUTH'])
if not profilelogged:
return HttpResponse('Unauthorized', status=401)
else:
index = request.GET.get('id', 0)
bookselected = Books.objects.filter(pk=index).first()
comments = list(Comments.objects.filter(book=bookselected).order_by('-date').all())
books_json = serializers.serialize('json', comments, use_natural_foreign_keys=True)
return HttpResponse(books_json, content_type='application/json')
Anyway I can get multimedia url on comment query on same response object serialized?
Thanks.
You are trying to convert ForeignKey object into JSON object which gives error as ForeignKey contains serialized data,
So you have to use safe parameter to convert your data into JSON.
return HttpResponse(books_json, content_type='application/json', safe=False)
if it doesn't work! Try this:
return HttpResponse(books_json, safe=False)
Otherwise you can always user JsonResponse as it is safer to user for propagation of JSON objects.
P.S:
Why your Profile ForeignKey in first Model is in quotes? Is it on purpose?
Thanks everyone.
I have reached what i want adding to the Profiles model natural_key function the Multimedia fields I want to use, insted of the full Multimedia model I do not need.
class Profiles(models.Model):
alias = models.CharField(max_length=40)
mail = models.CharField(max_length=255)
mainimg = models.ForeignKey(Multimedia, models.DO_NOTHING)
birthdate = models.DateTimeField(blank=True, null=True)
country = models.CharField(max_length=30, blank=True, null=True)
password = models.CharField(max_length=255)
terms = models.IntegerField(blank=True, null=True)
device_token = models.CharField(max_length=500)
def natural_key(self):
return (self.pk, self.alias, self.country, self.mainimg.pk, self.mainimg.url)
class Meta:
managed = False
db_table = 'profiles'
And now, the reponse is what I wanted.

Adding one to many relationship in Django models

I have two models in my Django-REST application.
a ProjectRequest and a ContactRequest
I want to make it so, each Projectrequest contains a list of the refered Contactrequests.
class ProjectRequest(models.Model):
project_name = models.CharField(max_length=50)
company_name = models.CharField(max_length=50)
#make array of technologiestechnologies = models.ArrayField(base_field=) (blank=True)
project_description = models.CharField(max_length=200)
project_type = models.CharField(max_length=30)
budget_estimation = models.IntegerField(
default=1000,
validators=[
MinValueValidator(1800),
MaxValueValidator(5000000)
])
#time_estimation = models.DateTimeField(default=None, blank=True, null=True)
class ContactRequest(models.Model):
topic = models.CharField(max_length=30)
description = models.CharField(max_length=200)
time = models.CharField(max_length=15)
project_request = models.ForeignKey(ProjectRequest,
on_delete=models.CASCADE)
so far I have established a relationship, with a foreign key, which works fine as of now. However I want to extends the functionality, so, that the ProjectRequest contains a list of all the projectrequest. I have tried with several different fields, without any luck, and the documentation I can only find fields for ManyToMany and OneToOne. How can this be achieved?
There are many ways to achive what you want. For that, lets add a reverse relation in model named contact_requests:
project_request = models.ForeignKey(ProjectRequest, on_delete=models.CASCADE, related_name="contact_requests")
Now you can use PrimaryKeyRelatedField to show Primary Keys of the ContactRequest attached to each ProjectRequest.
class ProjectRequestSerializer(serializers.ModelSerializer):
contact_requests = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = ProjectRequest
fields = ('contact_requests', 'company_name', ...) # other fields
Or if you want all the values of each contact_requests, then you can use nested relationship like this:
class ProjectRequestSerializer(serializers.ModelSerializer):
contact_requests = ContactRequestSerializer(many=True, read_only=True)
class Meta:
model = ProjectRequest
fields = ('contact_requests', 'company_name', ...) # and so on
You could add a property function to the ProjectRequest class that retruns all the ContactRequests that are related to that ProjectRequest like so...
class ProjectRequest(models.Model):
project_name = models.CharField(max_length=50)
company_name = models.CharField(max_length=50)
#make array of technologiestechnologies = models.ArrayField(base_field=) (blank=True)
project_description = models.CharField(max_length=200)
project_type = models.CharField(max_length=30)
budget_estimation = models.IntegerField(
default=1000,
validators=[
MinValueValidator(1800),
MaxValueValidator(5000000)
])
#time_estimation = models.DateTimeField(default=None, blank=True, null=True)
#property
def contact_requests(self):
return ContactRequest.objects.filter(project_request=self)
class ContactRequest(models.Model):
topic = models.CharField(max_length=30)
description = models.CharField(max_length=200)
time = models.CharField(max_length=15)
project_request = models.ForeignKey(ProjectRequest,
on_delete=models.CASCADE)
I had this problem too. This is how I solved it:
ContactRequest= models.ManyToManyField(ContactRequest,related_name="+")

How to display a foreign key value instead of the id?

I have the following models :
class FlightSchedule(models.Model):
tail_number = models.ForeignKey(TailNumber, null=False)
flight_number = models.CharField(max_length=30, null=False)
flight_group_code = models.ForeignKey(FlightGroup, null=False)
origin_port_code = models.ForeignKey(Port, null=False, related_name="Origin")
destination_port_code = models.ForeignKey(Port, null=False, related_name="Destination")
flight_departure_time = models.TimeField()
start_date = models.DateField()
end_date = models.DateField()
def __unicode__(self):
return u'%s' % self.flight_number
class Meta:
verbose_name_plural = "Flight Schedule"
class FlightScheduleDetail(models.Model):
flight_date = models.CharField(max_length=30, null=False)
flight_number = models.ForeignKey(FlightSchedule, null=False, related_name="flight_number_schedule")
route_id = models.CharField(max_length=30, null=False, unique=True)
flight_status = models.ForeignKey(Status, null=True, default=1)
def __unicode__(self):
return u'%s' % self.route_id
class Meta:
verbose_name_plural = "Flight Schedule Details"
and the serializer is as below :
class FlightScheduleDetailSerializer(serializers.ModelSerializer):
class Meta:
model = FlightScheduleDetail
fields = '__all__'
class FlightScheduleSerializer(serializers.ModelSerializer):
flight_number_schedule = FlightScheduleDetailSerializer(many=True)
class Meta:
model = FlightSchedule
fields = ['tail_number', 'flight_number', 'origin_port_code', 'destination_port_code', 'flight_departure_time',
'flight_number_schedule']
Here tail_number , flight_number is a foreign key. When I create an API, I get the response as the id of the fields. How can I display the name in the json?
My views.py is as below :
#api_view(['GET'])
def flight_schedule(request):
schedule = FlightSchedule.objects.all()
serializer = FlightScheduleSerializer(schedule, many=True)
return Response(serializer.data)
You can define the source with field_name in your serializer as follows.
I have used source='TailNumber.number'. Please use the right field_name in place of number
class UserProfileSerializer(serializers.ModelSerializer):
tail_number = serializers.CharField(source='TailNumber.number', read_only=True)
flight_number = ....(change as above)
class Meta:
model = FlightSchedule
fields = ['tail_number', 'flight_number', 'origin_port_code', 'destination_port_code', 'flight_departure_time',
'flight_number_schedule']
You could simply add them as if they were attributes.
flight_number_str = serializers.ReadOnlyField(source='flight_number.flight_number')
First flight_number is the attribute of FlightScheduleDetail, then the one of FlightSchedule
and then add it to the list of fields fields = [..., 'flight_number_str']
Otherwise you may have a look at nested relationships in DRF which can offer more possibilities also.
Another alternative is to use the depth option in a serializer. It is to specify nested serialization - doc
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
depth = 1
If users is a foreign key or manytomany key the serializer will display the users as an object and not as a key.
The depth option should be set to an integer value that indicates
the depth of relationships that should be traversed before reverting
to a flat representation.

Categories