Is is possible in the admin to pull a field from a remote model, if you have a local foreign key pointing to that model?
class FirstModel(models.Model):
[...]
value12 = models.CharField()
class SecondModel(models.Model):
[...]
firstmodel = models.ForeignKey(FirstModel)
And in the Admin I want to pull in value12, any time someone views/edits SecondModel. I figure I can do this through Inlines, but then I lose Fields and FieldSets ordering. Any other options? Ideal results would be sortable with fields/fieldsets, -and- read-only.
You should be able to access any field in the first model as: firstmodel__value12
For the list view for the SecondModel:
list_display = ('firstmodel__value12',)
For the edit view you can use formfield_overrides. To make it non-editable you specify a read-only widget, e.g. like this one or provide your own.
Related
I'm working on a Django project. where I need to map the fields using foreign key.
how to add only one field instead of whole table using foreign key ?
You can implement the __str__ method to specify how it should show the Developer object:
class Developers(models.Model):
# …
def __str__(self):
return self.Developer_Name
Note: normally a Django model is given a singular name, so Developer instead of Developers.
Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: developer_name instead of Developer_Name.
I have a foreign key, that when the object it references gets deleted will be filled with a default value via a callable on_delete=models.SET(callable).. However, I have problem with that because in the Django admin site I'm able to delete the callable value that it has passed to the foreign key and since my foreign key can't be null this is going to raise a server error which I don't like.. so I want to handle that error through the Django admin site itself if that is possible and I know it is.. also if you have better thoughts on this, I really appreciate your help.
As a temporary solution I had overrode the QuerySet > delete() method of the referenced model to skip deleting the object through the Django admin site bulk deletion. I'm sure that there is a better way than this.
The foreign key:
class Product(models.Model):
marektplace_tag = models.ForeignKey('tags.MarketplaceTag', on_delete=models.SET(default_marketplace_tag))
the callable:
# Model: Product
def default_marketplace_tag():
from tags.models import MarketplaceTag
tag = MarketplaceTag.objects.get_or_create(name='None')
return tag[0].id
The referenced model:
class MarketplaceTag(models.Model):
name = models.CharField(max_length=32, validators=[only_letters])
Hey i need to create a model from form. It's different way if i need to create a some another model, that have a relations with created object model from form. its must work like that -> i come on site, get form for create a model object and save new object. an then -> i have another model with relations with model from form. and i need, to create relation model object automaticly - when django taked new object from forms.
tried any can help me. i make it this way, but this time i have problem. -> i have manytomany field in my relation model, and i have manytomany field ->users from form. and i cant create a relation model with this instance :( Traceback:
TypeError at /ru/center/add/
Direct assignment to the forward side of a many-to-many set is prohibited. Use users_center.set() instead.
but i tired to try it(( help please, how i may do it?
views.py
for x in form['users_center'].data:
name_center = form['name_center'].data
fullname_center = form['fullname_center'].data
ogrn = form['ogrn_center'].data
head_center = form['head_center'].data # user id
many_users = form['users_center'].data
user_center = x # user id
new_center = Center.objects.create(name_center=name_center,
fullname_center=fullname_center,
ogrn_center=ogrn,
head_center=User.objects.get(id=head_center),
users_center=User.objects.get(id=int(x)))
new_center.save()
models.py
users_center = models.ManyToManyField(User,
related_name='center',
# through=CenterDetails,
default=None, blank=True,
verbose_name=_("Сотрудники"))
There is a join table implied by the many-to-many relationship between two models. The error is letting you know that you must set the relationship after creating a User object instead of trying to assign the relationship while creating the User object. You can use set() or add() to do this.
So try doing:
new_center = Center.objects.create(
name_center=name_center,
fullname_center=fullname_center,
ogrn_center=ogrn,
head_center=User.objects.get(id=head_center),
)
users_center=User.objects.get(id=int(x))
new_center.users_center.add(users_center)
Additionally it may be useful to rename your many to many field as a plural to indicate the relationship. Maybe users_centers instead. Since it seems like users can have many centers, and centers can have many users. That's up to you though, not required for it to work.
I have four models:
QuestStatus
AdventureStatus
QuestAdventureStatus (consists of two
things, foreign key fields to QuestStatus and AdventureStatus)
QuestAdventure (has the M2M relationship to QuestAdventureStatus)
I have a serializer for QuestAdventure and QuestAdventureStatus exists as a field on my serializer:
quest_adventure_status = serializers.ListField(source='quest_adventure_status.all', required=False)
How do I properly create a new QuestAdventure and create quest_adventure_status(es) as well (updating too)? For creating, quest_adventure_Status is mandatory, but when I pass in my instance it's already serialized and not model objects?
Is there a proper way to deal with this in DRF?
I'd suggest you taking a look at drf-writable nested: https://github.com/beda-software/drf-writable-nested
Let's say I have these models:
class First(models.Model):
id = models.SlugField(primary_key=True)
class Second(models.Model):
foo = models.ForeignKey('First')
This technically means that Second.foo is a SlugField that points to the primary key of First model.
The question is how can I access that raw value in foo without referencing and working with First model?
Bonus question: How to make this field searchable in Django Admin panel without pointing to a sub model field?
So how to do something like this?
#admin.register(Second)
class SecondAdmin(admin.ModelAdmin):
search_fields = ['foo_id',]
Instead of this?
#admin.register(Second)
class SecondAdmin(admin.ModelAdmin):
search_fields = ['foo__id',]
The answer to the main question is to add _id at the end of the variable that is being referenced:
Second.objects.filter(foo_id='something')