Proposal: meta labels on fields

I’ve been thinking about the boilerplate code that often ends up in packages like Ninja or DRF in order to do serialization and wondered if there was a way to shorten it. I’m wondering what people think about the following:

Add a “meta” argument to all fields and a get_meta_fields() method to the class. The meta argument would be a list, and a simple version could be a list of strings. A serializer could then introspect the Model for fields with a matching string meta label and construct the corresponding serialized class.

class Car(models.Model):
    make = model.CharField(max_length=20, meta=["NinjaIn", "NinjaOut"])
    vin = model.TextField(meta=["NinjaIn"])

Then Ninja could have code like:

in_serializer = make_serialzier(Car, "NinjaIn")

This would also work for Forms, or anywhere else this kind of class mapping occurs.

I could see a more complex version where “meta” also allowed a class that implemented some sort of registration classmethod which could be triggered by the Model constructor. I could also see the Meta inner class supporting an attribute or two that allowed you to mark all fields with the same label.

There could also be an alternate implementation, where instead of putting it on the field itself, it could be a set of nested dicts with this kind of meta label info in the inner class itself.

“meta label” might be a confusing name. Hoping someone more clever than I can come up with a better one if the idea is palatable.

I don’t think we should extend model fields with non-model info. They already contain form-level info like blank. The entanglement with forms which can be annoying when not using Django’s forms.

Also, you can implement custom metadata already with a wrapper utility. For your example:

class Car(models.Model):
    make = label_field(["NinjaIn"], model.CharField(max_length=20))

label_field could store the labels in a separate data structure like a defaultdict(list) from label to fields. Then other functions could use that. Thera nothing stopping Jinja or whatever from providing such tools already.

But personally I like the information to be separate. Models reflect what is in the database. Serializers or forms reflect the UI. Often there’s a close mapping but sometimes you need to vary them independently especially as projects get older.

1 Like