JSONFIeld(null=True): Is allowing null bad practice? - django

It's my first time working with Django's JSON fields. When going through examples I usually see the field implementations that set the default to an empty object.
However, for my purposes, I'd prefer to allow the field to be None as well. Since all the examples set a default, I'm not sure if allowing null will yield any negative consequences I'm unaware of currently.

Related

proto3 check if parameter is set

since in proto3 all parameters are optional when parameter is not set and message is deserialized then unset parameter holds default value. I can not find a way to check if the parameter has been set or not. Is there any way to find if parameter has been set similary as in proto2? I see that there is a method has_<param_name>() but it is private.
I don't think the distinction exists anymore in proto3. You are encouraged to have meaningful defaults.
But if you must, you can use a singular embedded message containing the value.
It seems after Protobuf 3.15.0 you could use hasField in C++ again:
According to the CHANGELOG:
Now Proto3 Oneof fields have "has" methods for checking their presence in
C++.
Building upon ramsay's answers, one thing that you can do if you have a real need for Null kind of value, is this:
import "google/protobuf/struct.proto";
message Test {
oneof value_or_null {
string value = 1;
google.protobuf.NullValue null = 2;
};
}
with the one of you will get the has_<param_name>() function back and you will be able to check if you have null or a value. Also this is a safer approach because you cannot set the two fields, the oneof implementation will make sure that potential previous field value get cleared and set the new one.
Do note however, that evolving oneof fields is trickier than evolving normal fields (you can see the potential problems here)
My recommendations
I would first make sure that there is a real need for Null and thus a real need for oneof.
I would try to make the default value of each field an invalid value in my business logic (eg: uint32 id with 0 value is invalid and I return an error)

How do I add an if statement to the postcondition of a schema?

I'll simplify things for this scenario (It's in Perfect Developer, it gets complex quite quickly). Let's say I have a simple schema in my class, called Succeed, which takes a Course (which is a previously defined class) as parameter.
Basically, I want to be sure that the course is in my courses set as a precondition, and then add it to my coursesCompleted set in my postcondition. This simple schema works great, and looks like this :
schema !Succeed(c:Course)
pre
c in allCourses
post
coursesCompleted! = coursesCompleted.append(c);
However, I want to add a quite simple if condition: If my coursesCompleted cardinality is 30 or more, I want to set a Diplomation enum to, let's say, "Ok". If the cardinality is less than 30, I will set it to "NotOk"
According to Perfect Developer's documentation, and all the rare examples I've seen, the if syntax should look like this :
if [condition1] : do stuff;
[condition2] : do other stuff;
fi
However, if I plug that directly in my schema, as is :
schema !Succeed(c:Course)
pre
c in allCourses
post
coursesCompleted! = coursesCompleted.append(c),
if [#coursesCompleted >= 30] : diplomation = Ok#DiplomationEnum;
[#coursesCompleted < 30] : diplomation = NotOk#DiplomationEnum;
fi
it does not work, I always end up with a "very descriptive"
Error! Syntax error at keyword 'if', expected one of: '!' '(' '?'
'c_address_of'
I've tried adding some ; everywhere, adding a via keyword after the post, changing it's position, trading ;s with ,, and a lot of other trial and error stuff.
So my question is: How can I add a if condition to a postcondition of a schema, in Perfect Developer?
Please answer in Perfect Developer. I (sadly) know my formal methods, I only need the if to compile in the worst tool in the world.
I can provide a solution in formal-methods using the zet notation, since I am not using Perfect Developer, however, that program should be based on formal-methods. As far as I know in formal methods, if conditions are not used when the system has different behavior over some preconditions, but rather you create 2 methods with different
preconditions(the way i implemented it) or a nested method covering both scenarios, seperated with a Logic OR in between. When it comes to error handling, you first provide a best case scenario and then define a robust method definition(schema calculus).
In formal methods the notation ! is used to describe the output while ? is used for the input.
I hope that this will help you understand possible issues, since its not a direct perfect-developer solution. However, considering the fact that in formal methods mathematics are used, you can use the following specification and jump to any program/language for the implementation part.
Note that: Anything that you will see in the following schemata on the preconditions/how the system changes part, is connected with a logic AND, however I am not using the symbol because is implied as far as a logic OR is not used.
So here is how it will look like in formal-methods(Z-notation).

Java's "UserContext" equivalent in Django

I'm writing REST services using Django Rest Framework. I want to keep some of the values like Language Code, AppId in a global variable (not static) and access it where ever I want. This may change for every request. In Java we call it as "UserContext". So that I can parse my header and assign the values into that and access it in Data or View Layer (for example). This will help me to avoid passing the values in every method. At the same it has to maintain life cycle for each request.
Is there anything like that in Django?
The plain answer is that django-tls (https://github.com/aino/django-tls) can make request available everywhere where you import it, and then you can just set attributes on request, request.user, or something similar.
That said, in 99% of the cases this is a bad idea, for instance if all you need it for is to avoid passing values to functions then it's extremely ill advised. You'll just make your code unreadable. If you have a lot of variables to pass around, maybe some of them need combining into some class?

Mix services and leaf objects in constructor for dependency injection?

I am attempting to make my code as testable as possible, which means using dependency injection correctly.
I have read that it's okay to use new() to instantiate an object, if that object meets certain criteria. Notably - it should not accept a "non newable" in its constructor.
For example, I should be able to go
new Form('signup');
because there is no way that my DI container would know how to create the "signup" form ahead of time.
I can make this work most of the time, but now I'd like the Form to be able to validate itself, using a third party validator, like:
$form->validate()->isValid();
...which means that I would have to pass in a validator service.
I'd really prefer to have the validator included already because most of the time the form will need to be validated, and I'd have to go through the extra work to set the validator on my own otherwise.
Is it okay, in this instance to do:
new Form(Validator $validator,$name);
I'd say that any value or object which an object requires in order to be in a valid state is one of that object's dependencies; in your example that would entirely validly include the form's name. I don't think the type of a dependency can be used to say whether it should be injected or not - Martin Fowler in this article for instance shows objects having strings injected into them, and DI containers can usually be configured to supply string values.
With this in mind, injecting the validator and the string is fine and entirely correct in my opinion.

What is the preferred Restful URI design to distinguish between a collection and singleton resource?

I have a URI structure which is hierarchical for a particular data set:
/Blackboard/Requirement/{reqID}/Risk/{riskId}/MitigationPlan/{planId}
If the url is split at various IDs you can get that particular resource e.g.:
GET: /Blackboard/Requirement/2/Risk/2
This gets Risk #2 associated with Requirement #2
The question is this: a desired feature is now to be able to update (PUT) and delete (DELETE) a set of requirements in the same HTTP request. (The entire 'set' of requirements is GET-able when you fire an HTTP GET to the /Blackboard URL - that's the default functionality since something is written on the blackboard, figuratively)
So should I create a new collection resource URL only supporting PUT/DELETE like this:
/Blackboard/Requirements : HTTP PUT/DELETE
(note the plural)
or actually make the existing URL structure plural
/Blackboard/Requirements/{reqID}/Risk/{riskId}/MitigationPlan/{planId}
The latter seems to break semantic uniformity since the other items in the hierarchy are singular. Should I make them plural too??
Does having an item id help disambiguate singularity (from a human perspective :) like Blackboard/Requirements/1 or is it preferable to expose a different resource (i.e., a collection) purely for operational reasons (since GET is not allowed without id - irrespective of it being singular or plural)?
Just wanted to know the opinions of the community on which approach is commonly chosen (or is the right way of doing it) for clarity cleaner design.
The latter seems to break semantic uniformity since the other items in the hierarchy are singular. Should I make them plural too?
You should want your url's to be cool. So if you do change them to make it match, make sure your old singular urls return redirects with the new locations. Determining the expensive of that might help make the decision of change/no-change. If your API isn't used yet, then there's no barrier one way or the other. IMO, I'd go for consistency.
Does having an item id help disambiguate singularity (from a human perspective :) like Blackboard/Requirements/1 or is it preferable to expose a different resource (i.e., a collection) purely for operational reasons (since GET is not allowed without id - irrespective of it being singular or plural)?
For me, it makes more sense to have the url collections plural even with id. That could be a bias from file systems though. In that sense, it only makes sense that a single resource would be deeper in the url than the collection resource. It also give an easy way back to the collection resource, a url breadcrumb.