Przejdź do treści
Biblioteka skilli
Programowanie · Budowanie i kod

add-field

/add-field

Dodaje pola do elementów domeny Protean (agregaty, encje, obiekty wartości): dobiera typ pola, konfiguruje walidacje i obsługuje pola asocjacji, jak HasOne, HasMany i ValueObject.

Repozytorium
protean ↗
Licencja
Apache-2.0
Ostatnia zmiana repozytorium
27.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
9
Skrypty
4
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 27.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

Co sprawdzić przed instalacją
  • 4 skrypty w paczce. Przejrzyj je przed instalacją, bo Claude może je uruchomić.

Skrypty: assets/add_association_fields.py, assets/add_field_with_custom_validator.py, assets/add_simple_field.py, assets/add_value_object_field.py

Co robi i kiedy

Dodaje pola do elementów domeny Protean (agregaty, encje, obiekty wartości): dobiera typ pola, konfiguruje walidacje i obsługuje pola asocjacji, jak HasOne, HasMany i ValueObject.

Wyzwalacze z opisu

add a fieldadd an attributeadd a propertyI need to store [data]add a new field to [aggregate/entity]
Oryginalny opis (EN)

Add fields to Protean domain elements (aggregates, entities, value objects). Guides you through selecting the right field type, configuring validations, and placing fields correctly. Use when the user asks to "add a field", "add an attribute", "add a property", "I need to store [data]", "add a new field to [aggregate/entity]", or describes data that needs to be tracked. Covers simple fields, association fields (HasOne, HasMany, ValueObject), field validation, custom validators, and choosing between field types for different use cases.

Jak działa

  1. Information to gather
  2. Process
  3. HasMany auto-generated methods
  4. Common mistakes
  5. Complete examples
  6. Detailed references
  7. Related skills
  8. Verify your work
Sekcje z nagłówków SKILL.md, w oryginale · 202 linii, 1 034 słów
Podgląd SKILL.md
---
name: add-field
description: Add fields to Protean domain elements (aggregates, entities, value objects). Guides you through selecting the right field type, configuring validations, and placing fields correctly. Use when the user asks to "add a field", "add an attribute", "add a property", "I need to store [data]", "add a new field to [aggregate/entity]", or describes data that needs to be tracked. Covers simple fields, association fields (HasOne, HasMany, ValueObject), field validation, custom validators, and choosing between field types for different use cases.
license: Apache-2.0
compatibility: "Requires Python 3.11+, protean framework"
metadata:
  author: proteanhq
  version: "0.1"
  category: workflow
  composes: [aggregate, entity, value-object]
  diagnostic_codes: [UNBOUNDED_INDEXED_STRING, UNINDEXED_FILTER_PATH]
---

# Add Field

Guide for adding fields to Protean domain elements: choosing the right type, configuring
parameters, and placing fields correctly.

## Information to gather

Before adding a field:

- [ ] **Target element**: Which aggregate, entity, or value object?
- [ ] **Data purpose**: What does this field represent?
- [ ] **Data type**: Text, number, date, boolean, relationship?
- [ ] **Required or optional?**
- [ ] **Default value?**
- [ ] **Validation rules?** Length, range, format, cross-field?
- [ ] **Relationship?** Is this a reference to another domain element?

## Process

### Step 1: Choose where the field goes

| Target | When | Patterns |
|--------|------|----------|
| **Aggregate** | Root domain object | See [aggregate](../aggregate/SKILL.md) |
| **Entity** | Child object within an aggregate (has identity) | See [entity](../entity/SKILL.md): always needs `part_of="AggName"` |
| **Value Object** | Immutable descriptive concept (no identity) | See [value-object](../value-object/SKILL.md) |

### Step 2: Choose the field type

#### Decision: Simple field vs ValueObject

**Use a simple field** when the data is a single value with no behavior:

```python
email = String(required=True, max_length=254)
price = Decimal(required=True, precision=19, scale=4, min_value=0.01)
```

Use `Decimal` for money. `Float` stores binary floating-point values, so amounts drift
when you add them up.

**Use ValueObject** when the data has multiple related attributes, behavior, or should
be reusable:

```python
@domain.value_object
class Money:
    amount = Decimal(required=True, precision=19, scale=4)
    currency = String(required=True, max_length=3)


@domain.aggregate
class Invoice:
    number = String(required=True, max_length=20)
    total = ValueObject(Money)  # amount and currency always travel together
```

**Rule of thumb**: If you see two fields that always travel together (amount + currency,
street + city), extract a value object. See [refactor-extract-value-object](../refactor-extract-value-object/SKILL.md).

#### Decision: HasMany vs List

**Use HasMany** for entities with identity and behavior:

```python
line_items = HasMany("LineItem")  # LineItem is an entity with its own identity
```

**Use List** for simple values without identity:

```python
tags = List(content_type=String)  # Just strings, no identity
```

#### Quick field type reference

| Data | Field type | Example |
|------|-----------|---------|
| Short text | `String(max_length=N)` | names, codes, statuses |
| Long text | `Text()` | descriptions, notes |
| Whole number | `Integer()` | counts, quantities |
| Money | `Decimal(precision=19, scale=4)` | prices, totals, balances |
| Measurement | `Float()` | weights, ratios, coordinates |
| True/False | `Boolean(default=True)` | flags |
| Date only | `Date()` | birth_date, expiry_date |
| Date + time | `DateTime()` | timestamps |
| Identity | `String(identifier=True)` | custom IDs |
| One child entity | `HasOne("Entity")` | one-to-one |
| Many child entities | `HasMany("Entity")` | one-to-many |
| Embedded VO | `ValueObject(VOClass)` | Money, Address |
| Link to another aggregate | `Identifier()` | `customer_id`, holds the other aggregate's id |
| Link back to the parent (aggregate root, or parent entity when nested) | `Reference("Order")` | on an entity, the reverse side of `HasMany`/`HasOne` |
| Simple list | `List(content_type=String)` | tags, codes |
| Key-value | `Dict()` | metadata |

### Step 3: Configure field parameters

```python
from protean.fields.validators import RegexValidator

# Required vs optional
name = String(required=True)
description = String()              # Optional (can be None)

# Defaults
status = String(default="draft")

# Constraints
sku = String(unique=True, max_length=50)
price = Decimal(precision=19, scale=4, min_value=0.01, max_value=999999.99)
quantity = Integer(min_value=1, max_value=10000)

# Enum-like choices
status = String(choices=["draft", "published", "archived"])

# Format validators
email = String(validators=[RegexValidator(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")])
```

### Step 4: Choose validation layer

| Rule type | Where | How |
|-----------|-------|-----|
| Single-field constraint | Field parameter | `Integer(min_value=1)` |
| Format validation | Validator | `String(validators=[RegexValidator(r"...")])` or a custom validator class |
| Cross-field business rule | `@invariant.post` on aggregate | See [add-validation](../add-validation/SKILL.md) |
| State-dependent guard | Method body | `if self.status != "DRAFT": raise ...` |

**Never duplicate**: if a rule can be expressed as a field parameter, don't also add an invariant.

### Step 5: Index fields you filter on, and bound the strings you index

If a repository filters on a field, add an index led by that field so the query does not
force a full table scan:

```python
from protean import Index

@domain.aggregate(indexes=[Index("email")])
class User:
    email = String(required=True, max_length=254)
    name = String(max_length=100)
```

An indexed `String` field should carry a `max_length`. An index over an unbounded string is
unportable: the DDL fails on SQL Server, needs a prefix length on MySQL, and is inefficient
on PostgreSQL. Size the length to the field's domain.

- **`UNINDEXED_FILTER_PATH`**: a repository filter on a field with no covering index. Add
  an index led by that field (`indexes=[Index("field")]`), or leave it alone when the table
  stays small or the query is a one-off.
- **`UNBOUNDED_INDEXED_STRING`**: an indexed `String` field with no `max_length`. Give it a
  bounded length, or drop it from the index if it does not need indexing.

## HasMany auto-generated methods

When you add `items = HasMany("LineItem")`, these methods are automatically available:

- `aggregate.add_items(item)`: add one or more items
- `aggregate.remove_items(item)`: remove an item
- `aggregate.get_one_from_items(id=item_id)`: get one item by keyword criteria. It raises
  `ObjectNotFoundError` (from `protean.exceptions`) when nothing matches and `TooManyObjectsError`
  when more than one item matches. It never returns `None`.
- `aggregate.filter_items(**criteria)`: get the items whose fields equal the given values.
  It matches equality only; operators such as `price__gt` are not supported.

**Never manually define these methods**: they exist automatically.

## Common mistakes

- **Wrong field type**: Use `Integer` for counts, `Decimal` for money and `Float` for measurements, not `String`. Use `Date`/`DateTime` for dates.

See [references/common-mistakes.md](references/common-mistakes.md) for detailed examples.

## Complete examples

- [Simple fields](assets/add_simple_field.py): Adding basic fields to an aggregate
- [Custom validator](assets/add_field_with_custom_validator.py): Field with custom validation
- [Association fields](assets/add_association_fields.py): HasOne, HasMany, and an `Identifier` link to another aggregate
- [ValueObject field](assets/add_value_object_field.py): Embedding a value object

## Detailed references

- [Field Types Guide](references/field-types.md): Comprehensive guide to all field types
- [Validation Strategies](references/validation.md): Field validation vs invariants
- [Association Fields](references/associations.md): HasOne, HasMany, ValueObject, Reference, cross-aggregate identifiers
- [Common Mistakes](references/common-mistakes.md): Anti-patterns when adding fields

## Related skills

- [aggregate](../aggregate/SKILL.md): Aggregate field patterns
- [entity](../entity/SKILL.md): Entity field patterns
- [value-object](../value-object/SKILL.md): Value object definition
- [add-validation](../add-validation/SKILL.md): Choosing the right validation layer
- [custom-validator](../custom-validator/SKILL.md): Building custom field validators
- [refactor-extract-value-object](../refactor-extract-value-object/SKILL.md): When fields should become VOs

## Verify your work

- [Verify with check](../../references/verify-with-check.md): run `check` and resolve what it reports
Pliki w paczce (9)
  • SKILL.md 9 KB
  • assets/add_association_fields.py 15 KB
  • assets/add_field_with_custom_validator.py 13 KB
  • assets/add_simple_field.py 8 KB
  • assets/add_value_object_field.py 14 KB
  • references/associations.md 13 KB
  • references/common-mistakes.md 9 KB
  • references/field-types.md 6 KB
  • references/validation.md 7 KB

Wersje

W bazie nie ma innych skilli o nazwie add-field.

Identyczna treść występuje jeszcze w 1 innych folderach na GitHubie. Tu pokazujemy jedną, najlepiej ocenioną kopię.

Migawka bazy z 13.11.2026 · wersja paczki d79a9a97e72f (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100projection
    Definiuje projekcję Protean, czyli zdenormalizowany model odczytu po stronie CQRS, przechowywany w bazie lub cache (np. Redis), z prostymi polami i polami ValueObject, bez referencji i asocjacji.
  • 100protean-overview
    Wprowadza agenta kodującego w domenę Protean przed pisaniem kodu: wyjaśnia podstawowe elementy (agregaty, encje, obiekty wartości, zdarzenia, komendy, handlery) i reguły, które je łączą.
  • 90custom-fields
    Dodaje, edytuje i porządkuje pola własne zadań, ich typy, wartości i widoczność na kartach zadań.
  • 100uw-analyze-domain
    Analizuje encje domenowe, obiekty wartości, agregaty i reguły biznesowe zakodowane w modelu, w ramach odtwarzania systemu.
  • 84design
    Prowadzi projektowanie domeny metodą DDD: encje, obiekty wartości i agregaty, w czterech fazach od zrozumienia do wdrożenia.
  • 100model-domain-aggregates
    Modeluje warstwę domeny ABP z klockami DDD: encje, korzenie agregatów, obiekty wartości, usługi domenowe, specyfikacje i zdarzenia domenowe, z kluczami GUID przez IGuidGenerator i zamkniętymi niezmiennikami.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.