Django using id to write foreign key fields - python

I need to have a CRUD interface for interconnected django models. Can i use _id fields to fill in ForeignKey fields? i.e. will this work:
class MyModel(models.Model):
foreign_key = ForeignKey('AnotherModel')
class MyModelSerializer(serializers.ModelSerializer):
foreign_key_id = serializers.IntegerField(write_only=True)
foreign_key = AnotherModelSerializer(read_only=True)
class Meta:
model = MyModel
fields = ('foreign_key', 'foreign_key_id')

Related

serialize write-only field which is not present in django model using viewset

I am using a django viewset and I want to serialize a field which is not in the model.
it is an extra field that would be passed by the user.
class Bank(models.Model)
name = models.CharField(max_length=255)
objects = models.Manager()
class BankSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(read_only=True)
name = serializer.CharField()
documents = serializers.ListField(write_only=True)
class Meta:
model = Bank
fields = ['id', 'name', 'documents']
def create(self, validated_data):
print(validated_data.get('documents'))
class BankViewset(viewsets.ModelViewSet):
serializer_class = BankSerializer
I am using a modelViewset for my view.
However I noticed that after I serialize, the documents field is missing

Exporting the fields of non-related with the model (Django Import-Export)

I am using Django-import-export on django admin.
I want to export the fields that are not related or are related over 2~3 relationship with the current model.
For example
Model Classes
class A(models.Model):
name = models.CharField(default=False)
category= models.CharField(default=True)
class B(models.Model):
title = models.CharField(default=False)
category = models.CharField(default=False)
Resource
class ResourceA(resources.ModelResource):
class Meta:
model = A
How can I get the fields on ResourceA, so that I can export the them to excel?

Foreign key value in Django REST Framework

models.py:
class Station(models.Model):
station = models.CharField()
class Flat(models.Model):
station = models.ForeignKey(Station, related_name="metro")
# another fields
Then in serializers.py:
class StationSerializer(serializers.ModelSerializer):
station = serializers.RelatedField(read_only=True)
class Meta:
model = Station
class FlatSerializer(serializers.ModelSerializer):
station_name = serializers.RelatedField(source='station', read_only=True)
class Meta:
model = Flat
fields = ('station_name',)
And I have an error:
NotImplementedError: RelatedField.to_representation() must be implemented.
If you are upgrading from REST framework version 2 you might want ReadOnlyField.
I read this, but it does not help me.
How to fix that?
Thanks!
RelatedField is the base class for all fields which work on relations. Usually you should not use it unless you are subclassing it for a custom field.
In your case, you don't even need a related field at all. You are only looking for a read-only single foreign key representation, so you can just use a CharField.
class StationSerializer(serializers.ModelSerializer):
station = serializers.CharField(read_only=True)
class Meta:
model = Station
class FlatSerializer(serializers.ModelSerializer):
station_name = serializers.CharField(source='station.name', read_only=True)
class Meta:
model = Flat
fields = ('station_name', )
You also appear to want the name of the Station object in your FlatSerializer. You should have the source point to the exact field, so I updated it to station.name for you.

How to rename ForeignKey set field in Django Rest Framework

I am serializing Foreign key set using Django Rest Framework, I have following models:
class Transaction(models.Model):
...
class TransactionStatus(models.Model):
transaction = models.ForeignKey(Transaction)
...
I have a serializer for both of these models, one of them looks like this:
class TransactionSerializer(serializers.ModelSerializer):
transactionstatus_set = TransactionStatusSerializer(many=True, read_only=True)
class Meta:
model = Transaction
depth = 1
fields = ('id', 'transactionstatus_set')
I want to have here a list of transaction statuses from back referenced _set queryset... But transaction_set just seems very awkward name in API for that..
After a quick experimenting I have discovered that this will do the trick:
class TransactionSerializer(serializers.ModelSerializer):
changes = TransactionStatusSerializer(many=True, read_only=True, source='transactionstatus_set')
class Meta:
model = Transaction
depth = 1
fields = ('id', 'changes')
Now I have a list of the statuses linked by foreign key with a nice name...

Django ManyToMany Inlines Ordering in 1.2.x

I'm using Django 1.2's new ManyToMany admin.TabularInline to display related objects in the admin app, and it works great except I can't figure out what to set the "ordering" property to so it can sort by one of the cross-referenced field names.
For instance:
class Foo(models.Model):
name = models.CharField(max_length=100)
class Bar(models.Model):
title = models.CharField(max_length=100)
foos = models.ManyToManyField(Foo)
class FooBarInline(admin.TabularInline):
model = Bar.foos.through
ordering = ('name', ) # DOES NOT WORK
raw_id_fields = ('name', ) # THROWS EXCEPTION
class FooAdmin(admin.ModelAdmin):
inlines = (FooBarInline, )
class Meta:
model = Foo
How can I get to the Foo.name field to order by it in the inline?
The model ordering meta option designates the order of the inline elements.
class Foo(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ('name',)
If you needed to have the ordering of the admin model different from your primary ordering, you could do something like this:
class Foo_Extended(Foo):
class Meta:
ordering = ('name',)
And use Foo_Extended for your AdminInline model.
I'm assuming you know this, but Django 1.3 adds and ordering option to the InlineAdmin model but I know you said Django 1.2
I think you may override
ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)
You can find details in the docs for ModelAdmin.formfield_for_foreignkey.

Categories

Resources