How can I add a changeable "subfield" to a ModelField in django?


I’m trying to create a kind of "subfield" for a CharField in django, but I’m not sure (a) if it is possible at all and (b) how to succeed if it is indeed possible.

Let’s say I want a model for Tools. They would have a, e.g., a field for long_name, short_name, maybe a ForeignKey for realizing different departments. One of these tools I’d like to be a Link, the said "subfield" being a URLField with the href to the webpage.

Now, I can create multiple link entries with the associated URL, but I’d rather have only one tool called "Link" with the changing URL attached. Is this a case for ForeignKey as well? Does it make sense to have a model with only one field (well, two if you count the pkid) in it?

Or am I on a completely lost path here?

Asked By: Martin K



If I’ve understood you correctly, you want to have a number of links that can be attached to a Tool model, so instead of just having a single URLField you would have a Many-to-One relation with a Link model:

class ToolLink(models.Model):
   url = models.URLField(...

class Tool(models.Model):
   links = models.ForeignKey(ToolLink, ...

The problem is that you only want one particular tool to be able to hold links. Your options are to create a ‘Tool’ base model that then has multiple different types of tool, like ‘StandardTool’, ‘LinkTool’, etc. or to setup some logic that monitors whether the Tool has links or not (or if another tool already has links) and whether creating links is acceptable.

Answered By: 0sVoid