My python code has fields named like field_name which is fine for python and works well with Django.
Lots of Javascript linters want you to make it fieldName or they whine at you a lot.
Trying to find a nice common ground between the two, I've written serializers like
class MySerializer(serializers.ModelSerializer):
fieldName = serializers.WritableField(source='field_name', required=True)
class Meta:
model = Widget
exclude = ('field_name',)
Problem is that this does NOT replace the external representation of field_name with fieldName, it sends both fieldName and field_name. So I told it to exclude the ('field_name'). Then when you are trying to save, it gets really upset because field_name isn't present, or fieldName isn't a member of the object.
I had thought that mapping would be a good way to do this, but it doesn't appear to be so. Is there someway to map the names from python -> javascript so the code can look pretty on both ends?
Found a package that takes care of it at the json level:
https://pypi.org/project/djangorestframework-camel-case/
Documentation is very sparse, but it appears to work, and integrating it is trivial (which might explain the sparse documentation).
You code should be working. So there's something missing from the example
The thing that comes to mind is your fields value — what do you have specified there? It's generally better to explicitly specify the fields you want there rather than using exclude — it takes longer to set up (maybe) but it'll save time in the long run.
If fieldName is included in fields and field_name is not I would expect your code to work.
(Perhaps show a little more if that doesn't solve it.)
Update after edit to question
Ok. Yes. You should specify the fields you want. Your fieldName is acting as an extra field with its source as field_name — this sort of thing is useful when using SerializerMethodField for example.
Update: Extra Solution
There's a ticket asking about Camel-casing field names for better compatibility with e.g. JavaScript clients. This links to a Gist with a working solution via custom renderer and parser classes.
Related
We're providing a public API that we use internally but also provide to our SaaS users as a feature. I have a Model, a ModelSerializer and a ModelViewSet. Everything is functional but it's blurting out the Model help_text for the description in the API documentation.
While this works for some fields, we would like to be a lot more explicit for API users, providing examples, not just explanations of guidance.
I realise I can redefine each field in a Serializer (with the same name, then just add a new help_text argument, but this is pretty boring work.
Can I provide (eg) a dictionary of field names and their text?
If not, how can I intercede in the documentation process to make something like that work?
Also, related, is there a way to provide a full example for each Viewset endpoint? Eg showing what is submitted and returned, like a lot of popular APIs do (Stripe as an example). Or am I asking too much from DRF's documentation generation? Should I handle this all externally?
To override help_text values coming from the models, you'll need to use your own schema generator subclass and override get_path_fields. There you'd be able to prioritize a mapping on the viewset (as you envision) over the model fields help_text values.
On adjusting the example generation - you could define a JSON language which just deals with raw JSON and illustrate the request side of things pretty easily, however, illustrating responses is difficult without really getting deep into the plumbing, as the default schema generated does not contain response structure data.
I'm reading some data from an excel file, and hydrating it into an object of class A. Now I have to make sure that one of the fields of the data corresponds to the Id of a specific Entity. i.e:
class A{
protected $entityId;
}
I have to make sure that $entityId is an existing id of a specific entity (let's call it Foo). Now this can be achieved using the choice constraint, by supplying the choices option as all of the existing ids of Foo. However this will obviously cause a performance overhead. Is there a standard/better way to do this?
I'm a bit confused about what you are doing, since you seem to talk about Excel parsing, but at the same time you mention choices, which in my opinion relate to Forms.
IMO you should handle directly the relationship to your entity, instead of only its id. Most of the time it is always better to have directly the related entity as attribute of your class A than only the id, and Symfony manipulates such behaviours pretty well.
Then just have your Excel parser do something like this:
$relatedEntity = $this->relatedEntityRepository->find($entityId);
if (!$relatedEntity) {
throw new \Exception();
}
$entity->setRelatedEntity($relatedEntity);
After doing this, since you were talking about Forms, you can then use an EntityType field which will automatically perform the request in database. Use query_builder if you need to filter the results.
I'm giving out a 'n' days free access to users when they sign up. Now I'd like to keep testing this value and would like to give out an interface for the admins so they can try it out without my intervention.
The obvious solution, atleast to me, was to define a new modal with a single field and retrieve the last value from this table.
class TrialTime
include Mongoid::Document
field :trial_time, type: Integer
end
and something like TimeTime.last.trial_time, only this looks inefficient to me.
Somehow I feel that configuration variables would be a better fit here. But I could not figure out how to persist this. Or am I completely over thinking this and the basic DB based solution is the right one?
I'm in a need to use beforeFind() in a child class of CActiveRecord.
Basically, I need to convert some data from before actual search in the DB is performed.
How do I alter the about-to-occur-find-operation that is about to take place, inside beforeFind()? Messing with $this attributes is not useful since its not even populated, which is a little surprise.
I've seen that the documentation mentions a "hidden CDbCriteria parameter" but I just couldn't guess how to use it... . Unfortunately, the documentation on this subject is slim.
What I need to do is rather simple: I've got a table column for storing IP addresses. The most efficient design from scalability perspective, is to use a VARBINARY(16) data type for the column. See for example this SO question page (and answers) on this.
So, the cleanest solution would be to have beforeFind(), afterFind() and beforeSave() work transparently for the users.
In the code stack, the IP addresses would be the normal dotted-quad and in the DB level, its whatever that goes into the field after utilizing PHP's inet_pton() method in those after/before hook methods.
It was supposed to be cool. and it is cool - with afterFind() and beforeSave(), where I have the ip_address attribute of the object at hand, at the mercy of my uber-manipulation powers.
Here's the point, and the need: thing is, I don't know how to achieve that on beforeFind(). I cannot do a blind mergeWith() as I need to check if ip_address attribute is part of the original criteria, and that I don't know how to do.
Help!
TIA :)
I've got this nice suggestion on yii forums.
Basically, I just need to override findByAttributes() in the child class and I'm done :)
I'm currently writing an application that plays podcasts. I'm representing all the feeds and the episodes within them as QStandardItem objects within a QStandardItemModel. Right now, I don't have a way to save this model--when the application closes, the feed model goes up in smoke. I looked at using QSettings, but that only works for datatypes that fall under QVariant.
Looking at this post gave me some hope, but I think I'm doing something wrong. I've got the following code in the constructor for my application.
//Expand QVatiant to use QStandardItemModel
qRegisterMetaType<QStandardItemModel>("QStandardItemModel");
That, however, gives me this error at compile time.
/ [...] QtSDK/Desktop/Qt/4.8.1/gcc/lib/QtGui.framework/Versions/4/Headers/qstandarditemmodel.h:424: error: 'QStandardItemModel::QStandardItemModel(const QStandardItemModel&)' is private
Ah. That reminds me of this caveat from the Qt documentation for QMetaType, here.
Any class or struct that has a public default constructor, a public copy constructor and a public destructor can be registered.
So, where do I go from here? Qt is behaving exactly as it should, so this approach won't work. I'm thinking of saving off the model as an xml file, but that seems like a ton of effort. This seems like a pretty common problem--I just don't know where to look for the answer.
Here's the best solution I could come up with: Create a method that saves the model into an XML document, and call it whenever I change the model (e.g. add or remove a podcast). I don't have the actual source code on hand, but since there's no real easy way to save the data structure wholesale, this is the best solution.