A GridFS storage field.
| 1833 | |
| 1834 | |
| 1835 | class FileField(BaseField): |
| 1836 | """A GridFS storage field.""" |
| 1837 | |
| 1838 | proxy_class = GridFSProxy |
| 1839 | |
| 1840 | def __init__( |
| 1841 | self, db_alias=DEFAULT_CONNECTION_NAME, collection_name="fs", **kwargs |
| 1842 | ): |
| 1843 | super().__init__(**kwargs) |
| 1844 | self.collection_name = collection_name |
| 1845 | self.db_alias = db_alias |
| 1846 | |
| 1847 | def __get__(self, instance, owner): |
| 1848 | if instance is None: |
| 1849 | return self |
| 1850 | |
| 1851 | # Check if a file already exists for this model |
| 1852 | grid_file = instance._data.get(self.name) |
| 1853 | if not isinstance(grid_file, self.proxy_class): |
| 1854 | grid_file = self.get_proxy_obj(key=self.name, instance=instance) |
| 1855 | instance._data[self.name] = grid_file |
| 1856 | |
| 1857 | if not grid_file.key: |
| 1858 | grid_file.key = self.name |
| 1859 | grid_file.instance = instance |
| 1860 | return grid_file |
| 1861 | |
| 1862 | def __set__(self, instance, value): |
| 1863 | key = self.name |
| 1864 | if ( |
| 1865 | hasattr(value, "read") and not isinstance(value, GridFSProxy) |
| 1866 | ) or isinstance(value, (bytes, str)): |
| 1867 | # using "FileField() = file/string" notation |
| 1868 | grid_file = instance._data.get(self.name) |
| 1869 | # If a file already exists, delete it |
| 1870 | if grid_file: |
| 1871 | try: |
| 1872 | grid_file.delete() |
| 1873 | except Exception: |
| 1874 | pass |
| 1875 | |
| 1876 | # Create a new proxy object as we don't already have one |
| 1877 | instance._data[key] = self.get_proxy_obj(key=key, instance=instance) |
| 1878 | instance._data[key].put(value) |
| 1879 | else: |
| 1880 | instance._data[key] = value |
| 1881 | |
| 1882 | instance._mark_as_changed(key) |
| 1883 | |
| 1884 | def get_proxy_obj(self, key, instance, db_alias=None, collection_name=None): |
| 1885 | if db_alias is None: |
| 1886 | db_alias = self.db_alias |
| 1887 | if collection_name is None: |
| 1888 | collection_name = self.collection_name |
| 1889 | |
| 1890 | return self.proxy_class( |
| 1891 | key=key, |
| 1892 | instance=instance, |
no outgoing calls
no test coverage detected