How would you inherit from and override the django model classes to create a listOfStringsField?

后端 未结 5 2080
轻奢々
轻奢々 2021-02-06 05:24

I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following:

models.py:

5条回答
  •  Happy的楠姐
    2021-02-06 05:46

    There's some very good documentation on creating custom fields here.

    However, I think you're overthinking this. It sounds like you actually just want a standard foreign key, but with the additional ability to retrieve all the elements as a single list. So the easiest thing would be to just use a ForeignKey, and define a get_myfield_as_list method on the model:

    class Friends(model.Model):
        name = models.CharField(max_length=100)
        my_items = models.ForeignKey(MyModel)
    
    class MyModel(models.Model):
        ...
    
        def get_my_friends_as_list(self):
            return ', '.join(self.friends_set.values_list('name', flat=True))
    

    Now calling get_my_friends_as_list() on an instance of MyModel will return you a list of strings, as required.

提交回复
热议问题