Skip to Content
Odoo Меню
  • Увійти
  • Спробуйте це безкоштовно
  • Додатки
    Фінанси
    • Бухоблік
    • Виставлення рахунку
    • Витрати
    • Електронні таблиці (BI)
    • Документи
    • Підпис
    Продажі
    • CRM
    • Продажі
    • POS Магазин
    • POS Ресторан
    • Підписки
    • Оренда
    Веб-сайти
    • Конструктор веб-сайту
    • Електронна комерція
    • Блог
    • Форум
    • Живий чат
    • Електронне навчання
    Ланцюг поставок
    • Склад
    • Виробництво
    • PLM
    • Купівлі
    • Технічне обслуговування
    • Якість
    Кадри
    • Співробітники
    • Рекрутинг
    • Відпустки
    • Оцінювання
    • Рекомендації
    • Автотранспорт
    Маркетинг
    • Маркетинг соцмереж
    • Email-маркетинг
    • SMS-маркетинг
    • Події
    • Автом. маркетингу
    • Опитування
    Послуги
    • Проект
    • Табелі
    • Виїзне обслуговування
    • Служба підтримки
    • Планування
    • Призначення
    Продуктивність
    • Обговорення
    • Схвалення
    • IoT
    • IP-телефонія
    • База знань
    • WhatsApp
    Сторонні модулі Odoo Studio Платформа Odoo Cloud
  • Сфери
    Роздрібна торгівля
    • Книжковий магазин
    • Магазин одягу
    • Магазин меблів
    • Продуктовий магазин
    • Магазин будівельних матеріалів
    • Магазин іграшок
    Food & Hospitality
    • Бар та паб
    • Ресторан
    • Фастфуд
    • Guest House
    • Дистриб'ютор напоїв
    • Hotel
    Real Estate
    • Real Estate Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Consulting
    • Accounting Firm
    • Партнер Odoo
    • Marketing Agency
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Екологічна агенція
    • Оренда білбордів
    • Фотографія
    • Лізинг велосипедів
    • Реселлер програмного забезпечення
    Browse all Industries
  • Спільнота
    Навчання
    • Навчальний посібник
    • Документація
    • Сертифікації
    • Тренування
    • Блог
    • Подкаст
    Сприяйте Освіті
    • Програма навчання
    • Бізнес гра Scale Up!
    • Відвідайте Odoo
    Отримайте програмне забезпечення
    • Завантаження
    • Порівняйте версії
    • Релізи
    Співпрацюйте
    • Github
    • Форум
    • Події
    • Переклади
    • Стати партнером
    • Services for Partners
    • Зареєструйте вашу бухгалтерську фірму
    Отримайте послуги
    • Знайдіть партнера
    • Знайдіть бухгалтера
    • Зустріньтеся з консультантом
    • Послуги з впровадження
    • Референси клієнтів
    • Підтримка
    • Оновлення
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Отримати демо
  • Ціни
  • Допомога

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Бухоблік
  • Склад
  • PoS
  • Проект
  • MRP
All apps
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Допомога

delete fields from database without uninstall?

Підписатися

Отримуйте сповіщення про активність щодо цієї публікації

Це запитання позначене
fieldsdatabase
4 Відповіді
32135 Переглядів
Аватар
Benjamin Bachmann

Hi I have a Add-on with a lot of Fields, I decided to delete a field.

I removed a the field but the field is still in the database. 

I searched google an they I only found that i have to uninstall the Add-on and reinstall it again, but then i loos all my data.

And I do not want to delete the field manually in the database, because there are several tausend entries. 

Any idea ? or a way that not existing field will be deleted?

2
Аватар
Відмінити
Yenthe Van Ginneken (Mainframe Monkey)

Perhaps another alternative is to hide the field from your view? If its purely for not wanting to show fields anymore this is an ideal solution.

Serpent Consulting Services Pvt. Ltd.

Its good to hide the fields, and not considering into any calculation if you fear the data!

Benjamin Bachmann
Автор

this solution would be fine, but if in the fields are sensible data like bank account numbers i do not want to just remove the view and the field. I want them deleted, so nobody can access them. And on the other way then i just remove the field my database stays big and will get bigger and bigger with a lot of junk data

Emipro Technologies Pvt. Ltd.

It is simply not possible to delete any fields without uninstall. For example if we delete from database, then once your py file gets compiled again those fields will be created or if you not restart your Odoo, you will face an error. Better to make them invisible (this is the only way to deal with your problem) via editing views ( form, tree, kanban etc...) From fields screen it is not possible to inactivate them because those may be exist in views. There is one module exists with it we can persist the data when you uninstall the module. You can try it out.

Emipro Technologies Pvt. Ltd.

@Benjamin, why you not delete the data by postgreSQL query, for the table on which there is sensitive data and then disable that field from view ?

Benjamin Bachmann
Автор

I think this is the only solution to write a script wich will delete all the fields on a new server start. I hoped there may be a odoo function or feature i did not know about.

Emipro Technologies Pvt. Ltd.

It's not solution, I wish your database is not in live usage when you go for this "lethal" experiment ;)

Yenthe Van Ginneken (Mainframe Monkey)

Backups will be the keyword here. :) Make sure that if you script something that it first takes a dump from your db before you start dropping records. Better save than sorry!

Аватар
Benjamin Bachmann
Автор Найкраща відповідь

I wrote the Script which cleaned the field:

If anyone have the same problem here a small example.


Check first in you database if you have the right field before deleting the field.

select * from ir_model_fields where model ='<Your Mode Name>' and name='<Your Field Name>'; 


Create a init xml which I put in the data folder.

<?xml version="1.0"?>
<openerp>
<data noupdate="1">

<function model="clean.field" name="init_remove_field_api7"/>

</data>
</openerp>


ADD a python file. (Do not forget to put it in your __init__.py file)

# -*- coding: utf8 -*-
from openerp import api
from openerp.models import TransientModel


class CleanField(TransientModel):

"""Initial Settings."""

_name = "clean.field"

# ToDo can be removed after field is deleted

def init_remove_field_api7(self, cr, uid, ids=None, context=None):
"""Entry function remove Field (called with API7)."""
return self._remove_field(cr, uid, context=context)

@api.model
def _remove_field(self):
"""Removes the Field from the database."""
self.env.cr.execute("""SELECT 1 FROM ir_model_fields
WHERE model = '<Your_Mode_Name>'AND name='<Your_Field_Name>';""")
fields = self.env.cr.fetchall()
if fields:
self.env.cr.execute("""DELETE FROM ir_model_fields
WHERE model = '<Your_Mode_Name>'
AND name='<Your_Field_Name>';
ALTER TABLE <The_Table_Name> DROP COLUMN <Your_Field_Name>;""")
self.env.cr.commit()
return True

7
Аватар
Відмінити
Yenthe Van Ginneken (Mainframe Monkey)

Good job and thanks for sharing this! +1

Emipro Technologies Pvt. Ltd.

Very good ! This was out of my mind at that time...

Emipro Technologies Pvt. Ltd.

+1

Benjamin Bachmann
Автор

made small safety changes

Аватар
FEDERICO LEONI
Найкраща відповідь

If you delete the database field with pgAdmin3 or directly from a console it should disappears with all his entries. Last time I've tried it worked fine if it is just in one table, don't do it if is a field related to another table.  Then you need to delete the field you dropped from the python file too.

In that way even if you rebuild your module the field will not shows again. It's a dirty hack, do a backup before doing it and pay attention with view definitions: if the field you deleted is till declared in a view Odoo will rise an error and could stop the server.

1
Аватар
Відмінити
Аватар
informatique@lotoquine.com
Найкраща відповідь

Hi,

Here's my version of Benjamin's solution for ODOO 10 :

xml :

< odoo>

< data>

 < function model="clean.field" name="init_remove_field_api7" eval="['account.indicateur.custom.ltq','total_achats']" / >

< /data>

< /odoo>

py file :

import logging
from odoo import models, fields, api, _, SUPERUSER_ID, tools
from odoo.models import TransientModel

_logger = logging.getLogger(__name__)

class CleanField(TransientModel):

""" Classe pour supprimer un champ de la BDD."""
_name = "clean.field"

@api.model
def init_remove_field_api7
(self, model_name="", field_name=""):
"""Entry function remove Field (called with API7)."""
if
model_name and field_name and type(model_name) == str and type(field_name) == str:
table_name = model_name.replace(".", "_")
_logger.info(u"init_remove_field_api7 : removing database field {}.{}".format(table_name, field_name))
return self._remove_field(model_name, field_name)
else:
return False

@api.model
def _remove_field
(self, model_name="", field_name="", context=None):
"""Removes the Field from the database."""
query1 = """SELECT 1 FROM ir_model_fields WHERE model = '{}' AND name='{}';""".format(model_name or "", field_name or "")
self.env.cr.execute(query1)
fields = self.env.cr.fetchall()
if fields:
table_name = model_name.replace(".","_")
query2 = """DELETE FROM ir_model_fields WHERE model = '{}' AND name = '{}';
ALTER TABLE {} DROP COLUMN {};"""
.format(model_name, field_name, table_name, field_name)
_logger.info(u"_remove_field : query = {}".format(query2 or "None"))
self.env.cr.execute(query2)
self.env.cr.commit()
return True




0
Аватар
Відмінити
Аватар
Maduka Sopulu
Найкраща відповідь

https://www.odoo.com/forum/help-1/question/delete-record-from-database-with-unlink-new-api-solved-73404

0
Аватар
Відмінити
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Реєстрація
Related Posts Відповіді Переглядів Дія
Why in Selection Field Only Key is Store in Database Not the Value ? Вирішено
fields database selection
Аватар
Аватар
1
груд. 24
2390
Share custom field between sale order to invoice
fields database customize
Аватар
Аватар
1
лип. 19
5171
Can't find some fields on database
fields database odoo10e
Аватар
Аватар
Аватар
3
січ. 18
9758
What is the best way to guarantee my model fields are added in the database, so I don't have to add them manually via SQL?
python fields database
Аватар
Аватар
1
груд. 16
4309
How to modify Many2many relation table Вирішено
fields database models
Аватар
Аватар
1
квіт. 16
11746
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
Open Source
  • Завантаження
  • Github
  • Runbot
  • Переклади
Послуги
  • Хостинг Odoo.sh
  • Підтримка
  • Оновлення
  • Кастомні доробки
  • Навчання
  • Знайдіть бухгалтера
  • Знайдіть партнера
  • Стати партнером
Про нас
  • Наша компанія
  • Торгові активи
  • Зв'яжіться з нами
  • Вакансії
  • Події
  • Подкаст
  • Блог
  • Клієнти
  • Юридичні документи • Конфіденційність
  • Безпека
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo - це набір програм для роботи з відкритим кодом, які охоплюють всі ваші потреби компанії: CRM, електронна комерція, бухгалтерський облік, склад, точка продажу, управління проектами тощо.

Унікальна пропозиція Odoo - це одночасно дуже проста у використанні та повністю інтегрована.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now